Catch Exception treatment

前端 未结 5 2024
情歌与酒
情歌与酒 2021-01-14 10:25

What\'s the difference between using

catch(Exception ex)
{
   ...
   throw ex;
}

and using

catch   //  might include  (Exc         


        
5条回答
  •  一向
    一向 (楼主)
    2021-01-14 11:19

    throw ex re-throws the exception object from that point. This is generally bad, since it destroys the useful call stack information which lead up to the original problem.

    throw releases the original caught exception, from the point it was actually thrown. It retains the call stack information up to that point, instead of to the point you caught.

    catch(Exception) and catch are essentially the same thing, except obviously the first gives you the exception object to do something with, and the second does not. But both will catch all exceptions. They are distinct from catch(SomeKindOfException), which will only catch exceptions of that specific type (or more specific types derived from that type). This is best for situations like:

    try
    {
        //some file operation
    }
    catch(FileNotFoundException fnfex)
    {
        //file not found - we know how to handle this
    }
    //any other kind of exception,
    //which we did not expect and can't know how to handle,
    //will not be caught and throw normally
    

提交回复
热议问题