Exception Code Processing

Source: Internet
Author: User

I often see my colleagues write code like this:

DataSet QueryDB ()
{
DataSet ds = null;

Try
{
// Do something
}
Catch (Exception ex)
{
// Logs must be recorded here
}

Return ds;
}

There are several questions:

1: Obviously, if the QueryDB method has any exception, the client cannot know it. For example, if the client calls the QueryDB method and the method returns null, does this mean that the database does not have this data? Or throw an exception?

2: Annotations should not exist. They should be replaced by real Log record code, such as Log. Write (ex );

3: This method captures all exceptions so that any exceptions are captured. this is inconvenient for development and never captures exceptions that you cannot handle.

4: Why do I write code like this ?? The explanation is: the real user does not want to see the error message. It sounds like a bit reasonable at first. Imagine that no user will use your software and then always throw an exception or something, but this is post-deployment, rather than development programmers don't want to see exceptions. During development, if you can see detailed exception information, you can quickly correct and fix bugs. Why not ??

So modify it as follows:

DataSet QueryDB ()
{
DataSet ds = null;

Try
{
// Do something
}
Catch (Exception ex)
{
Log. Write (ex );
Throw ex;
}

Return ds;
} Okay. Now the exception is caught and thrown.

Is there a problem with this code ??

In the catch Block, throw ex; it is best to change it to throw;

In. net, exceptions cannot be modified. When an exception is thrown, the stack trace information of the exception is reset,

Throw does not reset stack trace information, but throw ex; resets. Therefore, we recommend that you use the throw statement instead of throw ex to locate the exception throw location more easily. Otherwise, the clr considers the exception to be thrown in the catch statement block.

 

Related Article

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.