locked
throwing exceptions RRS feed

  • Question

  • User-1525009598 posted

    what is the difference between throwing an exception, and just saying "throw", i.e.

    throw ex;

    vs

    throw;

    Monday, January 27, 2014 2:09 PM

Answers

All replies

  • User-183374066 posted

    throw ex resets the stack trace (so your errors would appear to originate from HandleException)
    throw doesn't - the original offender would be preserved.

    http://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 27, 2014 2:16 PM
  • User71929859 posted

    When you throw an exception, then it reset the stacktrace and begin a new stracktrace from the point where exception occurs. When you do not specify any exception after the throw clause, it by default throw the current exception and does not reset the stack trace. Check below for mor detailed information

    http://blogs.msdn.com/b/jmstall/archive/2007/02/15/throw-vs-rethrow.aspx?Redirected=true

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 28, 2014 8:48 PM
  • User-760709272 posted
    catch (Exception ex)
    {
        // Both have the same result, only the first explicitly throws the exception that was caught
        // The second throws the exception that caused the catch block to fire
        throw ex;
        throw;
    }

    The explicit version of throw (the one where you throw an defined exception) is normally used when you want to generate an exception, or throw a different exception from the one caught.

    int i = int.Parse(someText);
    if (i < 1)
    {
       throw new ApplicationException ("Invalid input");
    }

    Tuesday, January 28, 2014 9:05 PM