Can you give me an example of implementation of .NET ‘try’ pattern?
Edit:
I don’t mean a “try-catch” statement, I mean a try patterns, like those used in TryParse(), and TryGetObjectByKey() methods.
Most specifically what to do with raised exceptions in custom ‘try’ pattern methods. Should I log it, should I ignore It. Does’ anybody know what is the practice with those methods?
Here is an example of using a TryXxx method:
Here is an example of defining the method:
Exception handling
Your method probably should avoid throwing any exceptions – if your user wanted exceptions they would use the non-Try version. You should therefore try to avoid calling methods which can throw when implementing your TryXxx. However some exceptions are unavoidable and could be thrown out of your control – for example
OutOfMemoryException,StackOverflowException, etc… There is nothing you can do about this and you should not try to catch these exceptions, just let them propagate to the caller. Don’t swallow them, don’t log them – that’s the caller’s responsibility.An example of this is
Dictionary<TKey, TValue>.TryGetValuewhen the key object provided to this method throws an exception whenGetHashCodeis called. Then the resulting exception is not caught inside theTryGetValuemethod – the caller will see the exception. This code demonstrates this happening: