Home > Programming > Making sure to handle all exceptions

Making sure to handle all exceptions

Usually if a library or a low level function throws an exception, there is a good possibility that it is handled somewhere. However if a GUI function (e.g. clicking a button) has an un-handled exception then the application goes down (crashes). In debug mode the debugger would point out the error but in release mode – the application plainly crashes, on the user’s desktop.

For GUI apps, this can be a concern.

Languages like Java are strict in this case. If a method declares that it can throw an exception, all the callers of the method are enforced to implement an exception handler. Code simply does not compile without handling the exceptions.

In .net you can do two things:

1. read the documentation and find out what kind of exceptions can be thrown. For example if you see the penbox library, every method does list the type of exceptions that can be thrown.

2. blindly add a handler for the “Exception” class – generic type and handles ‘any’ exception.

Approach # 2 is easy to implement. However it is not really a good practice. Exceptions should be really used in case of exception – something you do not expect to happen. Adding a common type of handler has the risk of losing valuable debug information. The exception might have pointed out a logic error (e.g. FormatException in converting strings to numbers). Using the appropriate handler, you can identify such cases during debug and fix the code. Using a generic type handler usually means that you are going to lose this information.

 Approach# 1 is really good. However it can be a pain to read the documentation.

 There is a new tool called “ExceptionHunter” from RedGate. It goes through your .net assemblies (exe or dll) and identifies what all places you have un-handled exceptions. There is a 15-day free evaluation if you want to check out.

Categories: Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: