Recommendation 60: Use inner when you re-throw an exception Exception
When you catch an exception, wrap it, or re-throw an exception, if it contains inner Exception, it helps the programmer analyze the internal information and facilitate the debugging of the code.
For example, in a distributed system, when communicating remotely, there are situations that can happen:
1) The network card is disabled or the network cable disconnects, this will throw socketexception, the message asks: "Because the target machine actively refused, unable to connect." ”
2) The network is normal, but the target host to be linked to no port is not in the listening state, this will throw socketexception, the message is: "Because the connecting party did not reply after a period of time or the connected host did not respond, the connection attempt failed. ”
3) The link time-out, the need to close the link through code, and throw socketexception, the message is: "The link exceeds the agreed duration." ”
In any of the above three cases, when returning to the end user, we need to wrap the exception message as "Network connection failed, please try again later".
So, the business approach of a distributed system should look like this:
Try { saveuser (user); } Catch (SocketException ex) { thrownew communicationfailureexception (" network connection failed, please try again later " , ex); }
When prompted for this information, we may need to log the original exception for the developer to analyze the specific reason (if this happens frequently, it could be a bug). When logging, it is necessary to log the internal exception or stack information that occurs with this exception.
throw New Communicationfailureexception (" network connection failed, please try again later ", ex); is to wrap the exception as a communicationfailureexceptionand pass the SocketException as a innerexception (i.e. ex).
If you do not intend to use innerexception, but to return additional information, you can use the exception Data property. As follows:
Try { saveuser (user); } Catch (SocketException ex) { ex. Data.add ("socketinfo"," network connection failed, please try again later " ); Throw ex; }
When capturing at the top, you can get exception information by key values:
Catch (SocketException ex) { Console.WriteLine (ex. data["socketinfo"]); }
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 60: Using inner when re-throwing exceptions Exception