Recommendation 59: Do not throw an exception in inappropriate situations
A common case where an exception is not easily thrown is an exception to the input and output that is within the controllable range.
Private void SaveUser3 (user user) { if0) { thrownew argumentoutofrangeexception ("agecannot be a negative number. "); } // Save user }
At least two of this method is defective:
1) The interpretation of age cannot be negative. This is a normal business logic and it should not be handled as an exception.
2) You should use Tester-doer to verify the input.
You should add a tester method:
Private BOOLCheckage (intAgeref stringmsg) { if(Age <0) {msg="Age cannot be a negative number. "; return false; } Else if(Age > -) {msg="Age cannot >100. "; return false; } return true; }
Calling code:
string string . Empty; if (Checkage (ref msg)) { saveuser (user); }
To master two principles:
- Normal business processes should not use exception handling.
- Do not always attempt to catch exceptions, but should allow exceptions to propagate on the call stack.
So, what exactly is the case that throws an exception?
Situation One
Throws an exception if a memory leak occurs after the code is run, if the resource is not available, or if the application state is not recoverable.
Let's look at a scenario that seems to be able to overturn the conclusion of the above example immediately. There are many similar codes in the console class provided by Microsoft:
if 1 - ) {thrownew argumentoutofrangeexception ("value") , Value, environment.getresourcestring ("argumentoutofrange_cursorsize" )); }
Or:
if NULL { thrownew ArgumentNullException ("value" ) ); }
Note, however, that this article refers to the following: No exception is thrown for input output that is within the controllable range. The difference lies in the word "controllable". The so-called "controllable" can be defined as: After an exception occurs, the system resources are still available, or the resource state can be restored.
The console class, while also providing the tester-doer pattern, allows callers to have more ways to validate the input. But never guarantee that the caller has enough knowledge of your class, and that he might call any of your public methods without considering the order, so some of the necessary exceptions should be thrown for such methods. However, if you write your own student business class, judging the age, the age is less than 0 such judgments, you should not throw an exception, because that is a normal flow of control.
Situation Two
When catching an exception, an exception is thrown if you need to wrap some more useful information.
This type of exception is particularly useful in the UI layer. The message that the system throws with the exception tends to be more technical in description, while in the UI layer, the exception user is most likely the end user. If we need to present the message information of the exception to the end user, it is better to wrap the exception and then throw a new exception with the friendly information.
Situation Three
If the underlying exception does not make sense in the context of a high-level operation, consider capturing these underlying exceptions and throwing new meaningful exceptions. If a invalidcastexception is raised as a new ArgumentException.
A typical example of a properly thrown exception is capturing the underlying API error code and throwing it. Looking at the console class, you'll also find a lot of places with similar code:
int errorCode = marshal.getlastwin32error (); if 6 ) { thrownew InvalidOperationException (environment.getresourcestring ( "Invalid operation_consolekeyavailableonfile")); }
The console encapsulates the error code returned by invoking the Windows API and causes the code to throw a new exception.
Obviously, when you need to invoke the interface provided by the Windows API or the third-party API, if the exception reporting mechanism of the other side uses the error code, it is best to re-raise the error provided by the interface, because you need to get your team to better understand these errors.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 59: Don't throw exceptions in inappropriate situations