Is that how you write your exception handling code?

  • 2020-05-10 18:42:38
  • OfStack

I often see colleagues write code like this:


DataSet QueryDB()
{
   DataSet ds=null;
   try
    {
         //do something
    }
    catch (Exception ex)
    { 
         // You're going to log it 
    }
    return ds;
}

Here are a few questions:

1: obviously, if there is any exception to the QueryDB method, the client cannot know. For example, if the client calls the QueryDB method, and the method returns null, what does that mean that there is no such data in the database? Or throw an exception?

2: comments should not exist, they should be replaced by real logging code, such as Log.Write (ex);

3: this method catches all exceptions so that any exceptions are caught, which is very inconvenient for development. Never catch exceptions that you can't handle.

4: why do you write code like this? The explanation is: real users don't want to see error messages. It sounds reasonable at first. Imagine that no user will use your software and throw an exception all the time. At the time of development, if you can see the detailed exception information, then can quickly correct, repair Bug, why not?

It was then modified as follows:


DataSet QueryDB()
{
     DataSet ds = null;
     try
     {
           //do something
     }
     catch (Exception ex)
     {
          Log.Write(ex);
          throw ex;
      }
      return ds;
}

Ok, now the exception has been caught and thrown successfully.

There is still a problem with this code.

In the catch block, throw ex; Better to change it to throw;

Because in.net, exceptions are immutable, and every time an exception is thrown, the stack trace of the exception is reset,

Throw does not reset the stack trace, but throw ex; Will be reset. Therefore, it is better to use throw statement rather than throw ex in order to find out where the exception is thrown. Otherwise clr would think the exception was thrown in the catch block.

By the way, don't catch exceptions that you can't handle. If you want the user to not see the exception in the future,

You can use AppDomain. Or Application's global exception handling.


Related articles: