tags:

views:

91

answers:

3

I sometimes see methods in the .net framework prefixed with "Try" e.g. int.TryParse(..).

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?

A: 

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.

Adam
+7  A: 

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
Oded
A: 

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.

tia