Let's also talk about "re-throwing exceptions" in C"

Source: Internet
Author: User

Almost all C # programmers write exception handling code like this.

Code 1:

1try
2 {ThrowException ();}
3 catch (Exception ex)
4 {throw ex ;}
5 finally
6 {}

If your underlying code has another method to throw an exception
Code 2:

1 public ThrowException ()
2 {
3 throw new Exception ("an underlying Exception ");
4}

Then, you may need to throw the underlying exception again.

If you use code 1, the exception stack trace will be interrupted. In VS2005, an exception is thrown (ex in code 1 ), instead of throwing underlying exceptions (new Exception in Code 2 ("One underlying Exception ");)

So how can we avoid interrupting abnormal stack traces and re-throwing underlying exceptions.
Code 3:

1try
2 {
3 ThrowException ();
4}
5 catch
6 {
7 throw;
8}

In this way, the underlying exceptions in Code 2 can be thrown again.
Of course, you can encapsulate underlying exceptions. The Code is as follows:
Code 4:

Try
{
ThrowException ();
}
Catch (Exception ex)
{
Throw new Exception ("underlying exceptions after PACKAGING", ex );
}

This will not interrupt the exception stack trace.
I have a little understanding, and I want to know more about it.

References: http://www.cnblogs.com/1landonsea/archive/2005/01/15/RethrowExceptionInCSharp.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.