Precautions for designing an exception Solution

Source: Internet
Author: User

"Yes ......" Describes the rules that must always be followed (but in special cases, they may need to be violated ).
"Think ......" It describes the rules that should be followed in general cases. If you fully understand the principles behind the rules and have good reasons not to follow them, do not fear breaking the rules.
"Don't ......" It describes some rules that should never be violated.
"Avoid ......" It is not so absolute. It describes the situations that are generally not good but some known violations.
× Do not return error codes.
The benefits of exceptions have been discussed in the previous section 1st, so exceptions are the main method to report errors. Remember that each exception has two types of information: one is the message attribute, and the other is the exception type. Exception Handling Program Decide what operations should be performed based on it.
√ Report operation failure by throwing an exception.
If a method fails to complete the task it should complete, it should be considered as a method-level operation failure and an exception is thrown.
√ Consider terminating the process by calling system. environment. failfast (New in. NET 2.0) without throwing an exception. If Code If you encounter a serious problem, you cannot continue to perform the operation safely.
× Do not use exceptions in the normal control flow. If you can avoid exceptions.
√ Consider the impact of throwing an exception on performance. For details, see section 7th.
√ To write a document for all exceptions, exceptions are essentially a violation of the implied assumptions of program interfaces. We obviously need to provide detailed documents on these assumptions to reduce the chance of exceptions caused by user code.
× Do not allow public members to decide whether to throw an exception based on a certain option.
For example:
// Poor design
Public type GetType (string path, bool throwonerror)
The caller is more difficult than the method designer to decide whether to throw an exception.
* Do not use exceptions as return values or output parameters of public members.
In this way, the benefits of reporting failed operations with exceptions will be lost.
× Avoid explicitly throwing exceptions from the finally code block.
√ Prioritize the use of existing exceptions in the system namespace, rather than creating new exceptions by yourself.
√ Use a custom exception type if the error handling method is different from other existing exception types.
For details about how to create a custom exception class, see section 5th.
× Do not create and use new exceptions only to own your own exceptions.
√ Use the most reasonable and targeted exceptions.
It is always wrong to throw a system. Exception. If you do so, think about whether you really understand the cause of the exception.
√ Rich and meaningful error messages should be provided when an exception is thrown.
It should be noted that the information is provided to other developers or end users. Therefore, the information should be designed based on Oriented objects.
√ Ensure that the syntax of the exception message is correct (natural language, such as Chinese and English ).
√ Make sure that each sentence in the exception message has a full stop.
This seems to be too detailed, so think about this situation: When we use the message information of the FCL predefined exception, have we put an end to it. If the information we provide does not have a full stop, will it be added when other developers use it?
× Avoid using question marks and exclamation points in abnormal messages.
Maybe we are used to using exclamation marks to "Warn" some operations have problems. ask ourselves what it feels like if the code we use returns an exclamation mark.
× Do not disclose security information in the exception message without permission.
√ Localized the exception information thrown by the component if you want the component to be used by developers who do not need (natural) languages.

6.2 handling exceptions
According to the discussion in section 6.1, we can decide when to throw an exception, select a suitable type for it, and design reasonable information. The next step is how to handle the exception.
If a Catch Block is used to capture an exception of a specific type and fully understand what it means to continue executing the Catch Block, we say this situation is to process the exception.
If the specific type of the captured exception is unknown (usually this is the case) and the Application continues to be executed without fully understanding the cause of the operation failure or responding to the operation failure, in this case, the exception is swallowed up.
× Do not capture uncertain exceptions (such as system) in the code of the Framework (a program used by developers. exception, system. systemexception), swallowed up the exception.
× Avoid swallowing errors when capturing uncertain exceptions (such as system. Exception and system. systemexception) in application code.
Sometimes it is acceptable to swallow exceptions in an application, but you must be aware of the risks. Exceptions usually result in inconsistent States. If you rashly swallow the exceptions and let the program continue to run, the consequences will be unimaginable.
× Do not exclude any special exceptions from the catch code block written to transfer exceptions.
√ Capture specific types of exceptions. If you understand the causes of exceptions and make appropriate responses to errors.
At this time, be sure that the program can be completely recovered from the exception.
× Do not capture exceptions that should not be caught. Generally, exceptions should be passed up the call stack.
This is extremely important. If exceptions that are not captured are captured, the bug is more difficult to detect. All Bugs should be exposed during development and testing.
√ Try-finally should be used for cleaning to avoid try-catch.
For well-written code, try-finally is more frequently used than try-catch. This may be contrary to intuition, because sometimes we may think: isn't a try a catch? We need to know that, on the one hand, we need to consider the consistency of the program status, and on the other hand, we need to consider the cleaning of resources.
√ Use an empty throw statement to capture and throw an exception again. This is the best way to keep the call stack.
If a new exception is thrown after an exception is caught, the reported exception is no longer an actual exception. Obviously, this is not conducive to program debugging. Therefore, the original exception should be thrown again.
× Do not use catch blocks without parameters to handle exceptions that are not compatible with Cls (not exceptions inherited from system. exception ).
Sometimes it doesn't make sense to pass the exception thrown by the underlying code to the high-level. At this time, you can consider encapsulating the underlying exception to make it meaningful to the high-level users. In another case, it is more important to know that the Code throws an exception, and the type of the exception does not matter. In this case, exceptions can be encapsulated.
√ Encapsulate the exceptions thrown at a lower level if the exceptions at a lower level are meaningless in a higher stage.
× Avoid capturing and encapsulating exceptions with unknown types.
√ You must specify an internal exception when encapsulating an exception ).
This is extremely important and will be helpful for code debugging.

6.3 use of standard exception types
× do not throw exceptions of the exception or systemexception type.
× do not catch exceptions of the exception or systemexception type in the framework (for other developers) Code unless you plan to throw them again.
× avoid exceptions of the exception or systemexception type, unless they are in the exception processor program at the top level.
× do not throw an exception of the applicationexception type or derive a new class from it (see section 4.2 ).
√ to throw an invalidoperationexception type exception if the object is in an incorrect state.
An example is to write data to a read-only filestream.
√ to throw argumentexception or its subclass, if the input is invalid. Be sure to use the type at the end of the inheritance level as much as possible.
√ set the paramname attribute when argumentexception or its subclasses are thrown.
This attribute indicates the parameter that causes an exception.

1: Public StaticFileattributes getattributes (StringPath)

2:{

3:If(Path =Null)

4:{

5:Throw NewArgumentnullexception ("Path",);

6:}

 
7:}

 

√ Use value as the name of the implicit value parameter in the attribute setting method.

 
1: PublicFileattributes attributes

2:{

 
3:Set

 
4:{

5:If(Value=Null)

6:{

7:Throw NewArgumentnullexception ("Value",);

8:}

 
9:}

 
10:}

× Do not let public APIs throw these exceptions.
If these exceptions are thrown, implementation details are exposed, and the details may change over time.
In addition, do not explicitly throw stackoverflowexception, outofmemeryexception, comexception, and sehexception. Only CLR can throw these exceptions.
7. Performance Considerations
We often have performance concerns when using exceptions, especially when debugging. Such concerns are reasonable. When a member throws an exception, the impact on performance is exponential. When we follow the previous specifications, we may still achieve good performance. Two modes are recommended in this section.

7.1 tester-doer Mode
Sometimes, we can break down a member that throws an exception into two members to improve the performance of the member. Next let's take a look at the Add method of the icollection interface.
Icollection numbers =...
Numbers. Add (1 );
If the set is read-only, the add method throws an exception. In scenarios where the add method often fails, this may cause performance problems. One way to mitigate the problem is to check whether the set is writable before calling the add method.

 
1:Icollection numbers =...

2:...

3: If(! Numbers. isreadonly)

4:{

 
5:Numbers. Add (1 );

 
6:}

The member used for testing the condition becomes the tester. Here is the isreadonly attribute. The member used to perform the actual operation and may throw an exception to become the doer. Here is the add method.
√ Use the test-doer mode in the method to avoid performance problems caused by exceptions, if this method is used in common scenarios, it may throw an exception (the frequency of exceptions is high ).
The premise is that the "test" operation is far faster than the "do" operation. In addition, it is dangerous to access an object through multiple threads.

7.2 try-Parse mode
compared with tester-doer mode, the try-Parse mode is even faster and should be used in APIs with extremely high performance requirements. This mode adjusts the member name so that the member's semantics contains a pre-defined number. For example, datetime defines a parse method. If the parsing string fails, it throws an exception and provides a corresponding tryparse method. If the parsing fails, false is returned, if the result is successful, an output parameter is used to return the result.
when using this mode, note that if the (method) operation fails due to reasons other than the try operation, an exception should still be thrown.
√ use the try-Parse mode in the method to avoid performance problems caused by exceptions. If this method is used in common scenarios, an exception may be thrown.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.