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.