In another article, I talked about custom exception handling in the. NET Exception Handling Mechanism. Today I want to talk about another exception handling method.
In the process of writing and processing program exceptions, different types of exceptions may occur, but different humanized prompts should be thrown. If the same prompts are thrown in a uniform manner, they will not be humanized,
Our general solution is:
- Public void Update ()
- {
- Try
- {}
- Catch (SqlExcetion ex)
- {
- Throw new excetion (ex );
- }
- Catch (IOExcetion ex)
- {
- Throw new excetion (ex );
- }
- // Other exceptions...
- Catch (Exception ex)
- {
- Throw new Exceptioin (ex );
- }
- }
Or use exception nesting (nesting exceptions in exceptions, so no code is available here)However, there is a problem with this method. If we have to handle it in multiple places, we will become a code worker. Therefore, use a class to manage it. Here we call it an exception handling class.
- /// <Summary>
- /// Global exception handling class
- /// Author: Database Home (http://www.uol123.com)
- /// </Summary>
- [Serializable]
- Public class ExceptioinManage: Exception
- {
- /// <Summary>
- /// Default constructor
- /// </Summary>
- Public parameter tioinmanage (){}
-
- Public parameter tioinmanage (string message)
- : Base (message)
- {
- Throw new Exception (message );
- }
-
- Public parameter tioinmanage (string message, Exception inner)
- : Base (message, inner ){}
-
- Public ExceptioinManage (System. Runtime. Serialization. SerializationInfo info,
- System. Runtime. Serialization. StreamingContext context)
- : Base (info, context ){}
-
- Public parameter tioinmanage (Exception ex)
- {
- If (ex. GetType () = typeof (System. Data. SqlClient. SqlException ))
- {
- // Log
- Throw new Exception ("the connection has been disconnected. Check the connectivity of the network !");
- }
If (ex. GetType () = typeof (System. IO. IOExcetion) {// log throw new Exception ("file cannot be read! ");}
// Other exceptions
- // Log (http://www.uol123.com)
- Throw ex; // default exception
- }
- }
In this way, we only need to change our throw new Excetion (ex) to throw new ExceptioinManage (ex) to throw a human-friendly exception! Fixed Link: c # custom exception handling (2) | Database Home + copy Link