Recommendation 67: Use custom exceptions with caution
Do not create a custom exception unless there is a good reason to do so. If you want to do something special with a class of programs, customize the exception. The reasons for customizing exceptions are as follows:
1) easy to test. By throwing a custom instance of the exception type, we can make the captured code know exactly what happened and restore it in a consistent manner.
2) Logical packaging. Custom exceptions can wrap multiple other exceptions, and then throw a business exception.
3) convenient caller code. Custom exceptions can make it easier for callers to handle business logic when writing their own class library or business layer code. For example, failure to save data can be divided into two exceptions, "Database connection Failed" and "network Exception".
4) Introduce a new exception class. This enables programmers to take different actions in the code based on the exception class.
Now for an example that requires the use of a custom exception, in an abstract factory, you can save the data settings in SQL Server or SQLite. The code snippet for the business layer is as follows:
Iuserdal dal = dataaccess.createuserdal (); Try { user user = dal. Getoneuser (); } Catch (Sqliteexception ex) { // handling SQLite exception } catch (SqlException ex) { // Handling SQL Server exception }
Although there are two exceptions to catch, it is clear that the code that handles the two exceptions is consistent. In addition, if future programs expand into data storage in Oracle, it is good to design a catch for Oracle. So in the respective data layer, you can create a custom exception dataaccessexception, and then let them each catch their own specific exception, throwing a common dataaccessexception.
For example, in the data layer of SQLite:
Public User getoneuser () { try { null; // querying the database gets the user return user; } Catch (SqlException) { thrownew dataaccessexception (); } }
The same is true for SQLite's data access layer. The business layer code at the beginning of this article can be changed to:
Iuserdal dal = dataaccess.createuserdal (); Try { = dal. Getoneuser (); } Catch (DataAccessException ex) { // Handling Data connection exception }
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 67: Use custom exceptions with caution