-2

I have two methods:

public void MethodOne() 
{

    try {
    MethodTwo();
    }
    catch (Exception ex) {
    Log.Message("Something went wrong);
    throw;
    }
}

public void MethodTwo()
{

    try {
    // Some logic that fails
    }
    catch (Exception ex) {
    throw ex;
    }
}

I'm calling MethodTwo from MethodOne. If a exception is thrown in MethodTwo. Will the program terminate after the exception has been handled there or will it bubble up to MethodOne and be catched there aswell?

user7388204
  • 57
  • 1
  • 7
  • 8
    why not just try it out using your debugger? – MakePeaceGreatAgain Jul 01 '20 at 13:10
  • 4
    For clarification, MethodTwo does not handle the exception, it throws it. Actually it throws a new one without the original's stack trace. If you debug you will see it bubbles up and you land in the catch block of MethodOne. – Crowcoder Jul 01 '20 at 13:10
  • 4
    What prevents you from hitting F5 and trying it out? Also, what do you think would happen to error handling such as logging if applications would terminate on the first `throw` they encounter? – CodeCaster Jul 01 '20 at 13:10
  • You may find this helpful: https://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex – MakePeaceGreatAgain Jul 01 '20 at 13:11

2 Answers2

0

The exception will be catched and rethrown in MethodTwo and then catched and rethrown again in MethodOne.

Whether the application will terminate depends on how and where you call MethodOne and whether you catch the exception when calling MethodOne or further up the call chain.

Note that throw ex resets the stack trace and should be avoided.

mm8
  • 163,881
  • 10
  • 57
  • 88
-1

The program will be terminated in MethodOne.

You can understand more from this article. Throw and Re-throw Exceptions in C#

Be aware, by throwing the exception will destroy the stack trace information!

D A
  • 1,724
  • 1
  • 8
  • 19