kejpa Posted May 11, 2004 Posted May 11, 2004 Hi there, can you Masters explain why I should use 'Finally' in my exception blocks? Try ' ... Some code .... Catch ee as Exception msgbox ("Repent") Finally ' ... Huh? Why? End Try ' More code Anything after the End Try block will be executed, won't it? As well as anything in the Finally block. Or am I missing something cruisial Confused, but struggling /Kejpa Quote
Administrators PlausiblyDamp Posted May 11, 2004 Administrators Posted May 11, 2004 How about if you didn't catch Exception but only selected sub-classes of Exception (i.e. DivideByZeroException) - as the error wasn't caught here the code after the finally block wouldn't execute but the finally block would still execute. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
kejpa Posted May 11, 2004 Author Posted May 11, 2004 That's something more that I didn't think about. Makes sense... Thanx for the lecture ;) Best /Kejpa Quote
*Experts* Nerseus Posted May 11, 2004 *Experts* Posted May 11, 2004 Also, even if your catch block were to throw an exception, the finally would still execute. A common example is: SqlConnection conn; try { conn = new SqlConnection("..."); } catch(Exception e) { throw new Exception("Couldn't open connection..."); } finally { conn.Dispose(); } Obviously not a very helpful block of code, but the conn.Dispose() line will execute even if the catch block throws an exception. Also, you can have a finally with no catch. It's common to use this in a method that changes a Windows cursor: this.Cursor = Cursor.Wait; try { // Do something time consuming here... } finally { this.Cursor = Cursor.Default; } In the above, you can have the cursor change back in the finally at the bottom. This is helpful if the code in the try block may exit early ("return;" in C#). If you have 3 or 4 exit points in the try block, you don't want to have to reset the Cursor each time. -Nerseus Quote "I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
kejpa Posted May 12, 2004 Author Posted May 12, 2004 This is helpful if the code in the try block may exit early ("return;" in C#). If you have 3 or 4 exit points in the try block, you don't want to have to reset the Cursor each time. SO, the Finally block executes even if I return in the catch or try blocks. Great! Alright, finally I get it ;) Thanx a bounch. /Kejpa Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.