Quick tip: Do proper exception handling
This might be a bit of a d’oh, but if you decide to handle exception, handle it properly. What do I mean by saying “properly”? Have you ever seen code like this?
var myClass = new MyClass(); try { myClass.SomeMethodThatCanThrowException(); } catch { } finally { myClass.Dispose(); }
This code is stupid. Exceptions are a sign of exceptional or unpredicted behaviour. Thus, they should be treated with all seriousness. The code above works fine, if no exception is thrown. However, we live in unpredictable world. Internet connection may die. Hard drive may crash. Computer can run out of memory. And, in the case above, as soon as exception is thrown, neither you nor user will have the slightest clue of what went wrong.
There are two ways to solve this:
- Re-throw exception using
throw;
statement and handle it later on or - Handle it in
catch
part of statement.
I understand that sometimes you just don’t see the need to handle an exception, but the least you can do is write the exception to log file.
Leave a Reply