Thursday, July 07, 2005

Exception handling

Finally, before the party and adding these blogs, I went to a session on Exception handling by David Platt, an author and tutor at Harvard. Brilliant!! very very good presenter!

Basically, Exception handling is expensive, partly based on the fact it has to walk the stack TWICE for every exception.

1. Looking for a handler
2. Looking for a finally block

So...........

A. Repurpose by using cheap methods. Int32.TryParse instead of Int32.Parse or use File.Exists() instead of looking for the FileNotFound exception

B. Avoid overthrowing - that is catching an exception and then throwing it again. It loses information and you should only catch exceptions you can handle. Options include

i) Put a finally block in
ii) Retrhow and exception using throw;
iii) wrap using an inner exception - throw new Exception("Something", e)

C. Avoid overcatching - only catch those exceptions you can do something about. Otherwise your just hiding exceptions.

You want to know about bugs, so does your user, so DON'T HIDE THEM

D. use windows winqual.microsoft.com feature to send and have the ability to report on unhandled exceptions, thrown by your app.

E. NOTE: If you impersonate a user for some code and you run some code that you dont trust that has setup a Filtered Exception, a FINALLY block you have defined will not be called until the exception filter has been called. The Exception Filter is running within the context of your impersonated user and so can be malicious and have unwanted rights! bewarned!

Good presentation, nice topic.

My tip - an Exception by its very meaning is something that doesn't happen often, so treat it as such. Use cheaper methods for those errors that are more likely to occur, for example, return a boolean value

0 Comments:

Post a Comment

<< Home