In fact, I'd argue that you should normally see the finally keyword in an application far more often than the catch keyword - or at least the finally keyword in disguise via using or lock which both emit a try ... finally block under the covers.
There is only any point in trying to catch an exception if you can do something about it - so maybe a user has slected a file to open and that file is locked by another process. Its worth catching the FileIOException and telling the user so they can close the other process and retry. But what should you do about a NullReferenceException?
Obviously you would want to handle this exception *somewhere* so the user doesn't just see ann unhandled exception but you probably in this case just want to take the application down gracefully logging the problem.
finally blocks on the other hand (either explicit or implicit ones generated by using and lock) are a fundemental requirement to ensure robust resource cleanup for methods, therefore, you should have many more of them than catch blocks.
Regards
Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog http://www.dotnetconsult.co.uk
On 30 Nov 2004 01:29:51 -0800, Tilfried Weissenberger wrote:
I am a bit confused as to what the FINALLY block is meant for.
What's the difference between:
this.Cursor = Cursors.WaitCursor;
try { //do some stuff }
catch { //handle exception }
finally { this.Cursor = Cursors.Default; }
and this one:
this.Cursor = Cursors.WaitCursor;
try { //do some stuff }
catch { //handle exception }
this.Cursor = Cursors.Default;
One of the most common scenarios where you would see the difference is if
an exception occurred in your catch statement. Say in your catch you
wanted to log the exception to the event log or to an application log file,
but a permission or some other error occurred and an exception was thrown
while trying to log the initial exception. In that case, with your second
example the resetting of the cursor would not be executed. In your first
example it would be executed.
--
Tom Porterfield
=