0

Let's suppose we have such code:

int x = 0;

try
{
    try
    {
        x /= x; // DivideByZeroException
    }
    finally
    {
        throw new OverflowException("foobar"); // how to pass thrown exception here
    }
}
catch(Exception e)
{
    System.Console.WriteLine(e.Message);
}

Is it possible to get thrown exception in finally and pass it as a second argument of OverflowException?

UPD: guys, I do know how to work with catch and I do know that it is weird practice to throw an exception from finally.

But the original quesition (which definitely has science nature, not practical) can we retrieve thrown exception in the finally?

Yes (then how)? No? That's all I wanted to see.

zerkms
  • 249,484
  • 69
  • 436
  • 539

3 Answers3

1

It's usually considered a bad idea to throw from a finally. This is because it hides the first exception. See this stackoverflow post.

This might be better:
try
{
    try
    {
        x /= x; // DivideByZeroException
    }
    catch (DivideByZeroException dbze)
    {
        throw new OverflowException("foobar", dbze); // how to pass thrown exception here
    }
}
catch(Exception e)
{
    System.Console.WriteLine(e.Message);
}
Community
  • 1
  • 1
agent-j
  • 27,335
  • 5
  • 52
  • 79
0

I think you just want to catch it in a catch, and then rethrow it or another exception with whatever values you want as parameters. Why do you want to do this with a finally?

Marvo
  • 17,845
  • 8
  • 50
  • 74
0

the practice is to catch specific exceptions first, then more generic. the finally should only be used to "clean up" any objects used within the try block. for example, if you have logic that only has to happen for a OverflowException, try

try
{
  // do stuff
}
catch(OverflowException ex)
{
  // do specific stuff here
}
finally
{
  //clean up here
}

doing this, you allow non overflow exceptions to fall through, allowing other calling code to handle any resulting issues. this is preferred because the exception will have the full trace stack in the location needed. Following your code in the question, the stack trace of the Overflowexception you are throwing would only start within your current method, not within the code that caused the exception in the first place.

Now, if you just want to throw the OverFlowException after doing your work, use the

throw;

keyword, not the

throw ex;

command. See this blog post for a better description

Nathan Tregillus
  • 6,006
  • 3
  • 52
  • 91
  • note, whether you eat the exception in the catch block, re throw the exception, or throw a new exception, the finally block will always be called. – Nathan Tregillus Jun 21 '11 at 22:28