Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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

  • Administrators
Posted
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.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

  • *Experts*
Posted

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

"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
Posted
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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...