Is there a difference between “throw” and “throw ex”?

前端 未结 10 2355
夕颜
夕颜 2020-11-22 01:08

There are some posts that asks what the difference between those two are already.
(why do I have to even mention this...)

But my question is different in a way

10条回答
  •  伪装坚强ぢ
    2020-11-22 01:48

    Look at here: http://blog-mstechnology.blogspot.de/2010/06/throw-vs-throw-ex.html

    Throw:

    try 
    {
        // do some operation that can fail
    }
    catch (Exception ex)
    {
        // do some local cleanup
        throw;
    }
    

    It preserve the Stack information with Exception

    This is called as "Rethrow"

    If want to throw new exception,

    throw new ApplicationException("operation failed!");
    

    Throw Ex:

    try
    {
        // do some operation that can fail
    }
    catch (Exception ex)
    {
        // do some local cleanup
        throw ex;
    }
    

    It Won't Send Stack information with Exception

    This is called as "Breaking the Stack"

    If want to throw new exception,

    throw new ApplicationException("operation failed!",ex);
    

提交回复
热议问题