The main difference between the two lies in the output stack trace:
- If you directly use throw;, the stack trace is the same as when the Catch Block does not exist at all. The root cause of the error is that the exception is thrown.
- If you use throw ex;, stack trace considers that the exception you caught has been handled, but a new exception is thrown during the process. In this case, stack trace sets throw ex; as the root cause of the error.
Obviously, the latter will reduce the amount of stack trace information, which increases the difficulty of tracking error sources, so it is best not to do so. If you want to catch the exception, and then you want to let the exception continue to bubble up, you have another option besides throw ex:
Try
{
Methodthatthrowsexception ();
}
Catch (exception ex)
{
Throw new exception ("Oops! ", Ex );
}
At this time, You encapsulate the original exception into the newly thrown exception, and stack trace automatically considers the internal exception as the cause of the current exception, the stack trace with internal exceptions is also displayed recursively.
Some people often use the following methods:
Try
{
Methodthatthrowsexception ();
}
Catch (exception ex)
{
Throw new exception ("an unknown exception or something ");
}
If this is done, the error is blocked, so that the upper layer cannot know what is going on here, so it is best to follow the above two methods to handle the exception.
One is direct re-throwing. The other is encapsulation.
Today, the actualCodeTested
1. Throw;
2. Throw ex;
3. Throw new exception ("");
4. Throw new exception ("", ex );
These four exceptions are re-thrown... Summarized as follows (in. NET 1.1 environment)
Only throw new exception ("", ex) can be directly located in the place where an exception error code occurs. Others cannot be located and can only be located in the place where the exception is thrown.
Throw new exception ("") completely swallowed the exception. Only display the information in the exception ..
The throw and throw ex are exactly the same, and there is no difference. The exception information can be displayed normally, but the code for the exception may only be set to throw the exception.
Therefore, throw, throw ex, and throw new exception ("", ex) are basically correct. Do not use the throw new exception ("") method when writing class library code, it will completely swallow the exception, and the upper-layer calling code has no idea what exception will happen.
The other three methods are used. I personally think the difference is not. However, throw new exception ("", ex) can be added with custom exception information. Easy to identify errors