Is there a "Try" convention?
I sometimes see methods in the .net framework prefixed with "Try" e.g. int.TryPars开发者_如何学JAVAe(..).
I assume this means that the method is the same as a int.parse, but wrapped in a try catch?
Does this mean that if I write methods which have a try catch around them (e.g logging, which I never want to raise an exception), they should be prefixed with "try" as well?
Your assumption may be correct, but this is not the meaning of the Try***
type methods.
The promise is indeed that the method will no throw an exception (how this is managed internally does not matter) when called.
You will notice that these methods return a boolean indicating whether the Try***
was successful or not.
The TryParse
methods specifically have an out
parameter that will be populated with the result of the parse if successful.
To answer the questions directly:
- There is no specific convention
- If the semantics of the method mean that an exception will not be thrown but the calling code will be informed of success/failure, you can name it
Try***
as this is the kind of behavior implied by such a name
There isn't a convention in the same sense as asynchronous operations (BeginXXX EndXXX), however it is used to differentiate between code that will do the same as other code, but does not throw exceptions, either by swallowing exceptions or not generating them.
If your code is an alternative to another method that does not provide exception handling, I would prefix it with Try because it is somewhat recognised - and .NET people will first assume it's behaviour will not throw exceptions.
This can be re-inforced by returning a bool for success and placing the return value as an out parameter.
To answer the question - it shouldn't just be placed around any method that handles exceptions; only in instances where it makes sense logically to offer the behaviour I outlined; the behaviour currently offered by some instances in the .NET Framework.
The int.TryParse method is NOT equivalent to wrapping try/catch to int.parse in terms of performance. The purpose of int.TryParse is to avoid performance impact causes by exception throwing, so there's no point implementing int.TryParse as int.parse wrapped with try/catch.
精彩评论