Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch Block Choices

Tags:

c#

exception

I am reading C# article.It suggests that

At the end of the catch block, you have three choices:

• Re-throw the same exception, notifying code higher up in the call stack of the
exception.

• Throw a different exception, giving richer exception information to code higher up in the call stack.

• Let the thread fall out of the bottom of the catch block.

I am unable to understand the points.It would be a great help, if you clarify it by giving simple example.

Thanks in advance.

Update : When i need to handle rethrown exception ,do i need to have nested try .. catch blocks like

try
{
   try
   {
   }
   catch(InvalidOperationException exp)
   {
     throw;
   }

}
 catch(Exception ex)
 {
    // handle the exception thrown by inner catch block
   // (in this case the "throw"   clause     inside the inner "catch")
 }
}
like image 919
user184805 Avatar asked May 23 '26 15:05

user184805


1 Answers

Well, here are those different options in code:

Option 1: Rethrow

try
{
    // Something
}
catch (IOException e)
{
    // Do some logging first
    throw;
}

Option 2: Throw a different exception

try
{
    // Something
}
catch (IOException e)
{
    // Do some logging first
    throw new SorryDaveICantDoThatException("Oops", e);
}

Option 3: Let the thread fall out of the bottom

try
{
    // Something
}
catch (IOException e)
{
    // Possibly do some logging, and handle the problem.
    // No need to throw, I've handled it
}

EDIT: To answer the extra question, yes - if you need to handle a rethrown exception, that needs to be handled in an outer scope, exactly as shown in the question. That's very rarely a good idea though. Indeed, catch blocks should relatively rare in the first place, and nested ones even more so.

like image 169
Jon Skeet Avatar answered May 26 '26 04:05

Jon Skeet