What happens if an exception occurs in Catch block in C#. Also what would be the caller result in that case
An exception thrown in a catch
block will behave the same as an exception thrown without it - it will go up the stack until it is caught in a higher level catch block, if one exists. Doing this is quite normal if you want to change or wrap the original exception; i.e.:
public void MyStartMethod
{
try
{
//do something
MyBadMethod();
}
catch(MySpecialException mse)
{
//this is the higher level catch block, specifically catching MySpecialException
}
}
public void MyBadMethod()
{
try
{
//do something silly that causes an exception
}
catch (Exception e)
{
//do some logging
throw new MySpecialException(e);
}
}
public class MySpecialException : Exception
{
public MySpecialException(Exception e) { ...etc... }
}
In your case, myResult
will have whatever value it had before, if it's even still in scope.
The info below will help (from a previous answer of mine to a related question). If your catch block throws an exception and there are no other catch blocks to handle it besides the one that caused it, it will continue to get re thrown then 'Windows handles it'.
If a exception occurs the CLR traverses up the call stack looking for a matching catch expression. If the CLR doen't finds a matching one, or the Exception gets re thrown each time, the Exception bubbles out of the Main() method. In that case Windows handles the Exception.
Event Handling of Console Applications is the easiest to understand, because there is no special Handling by the CLR. The Exception is leaving the Applications Thread if not caught. The CLR opens a window asking for debug or exit the application. If the user chooses to debug, the debugger starts. If the user chooses to close, the Application exits and the Exception is serialized and written to the console.
An exception in the catch will basically behave as if there was no catch block there to begin with. You see this pattern in multilayered code where you rethrow exceptions. This is a slight variation on your example, but the result is very similar.
try
{}
catch
{
throw;
}
In the case above and in your case the exception is considered unhandled since it's still propagating up the stack.
There will be no return value. The program simply fails if there is no other catch block to deal with it.