Best practices for Exception Handling

Source: Internet
Author: User
Tags finally block

A well-designed error handlingCodeThe block set allowsProgramIt is more robust and faces fewer crash opportunities because such applications process errors. The following list contains suggestions for best practices for exception handling:

  1. Know when to set up a try/Catch Block. For example, you can program to check conditions that may occur outside of exception handling. In other cases, exception handling should be used properly to capture error conditions.

    The following example uses an if statement to check whether the connection is closed. You can use this method to throw an exception if the connection is not closed.

    If (conn. State! = Connectionstate. Closed) Conn. Close ();

    In the following example, an exception is thrown if the connection is not closed.

    Try {conn. Close ();} catch (invalidoperationexception ex) {// do something with this error or ignore it. }

    The method you choose depends on how you often expect the event to be generated. If the event is a real exception and an error (such as the end of an unexpected file), it is better to use exception processing, because only less code will be executed in the regular scenario. If this event occurs frequently, it is best to use a programmable method to check for errors. In this case, if an exception is generated, the exception will take a longer time to process.

  2. Use try/Finally block to enclose codes that may cause potential exceptions and concentrate your catch statements in one place. In this way, the try statement will generate an exception, and the finally statement will close or cancel the resource allocation, and the catch statement will also handle the exception from a centralized location.
  3. Always sort exceptions in catch blocks in the most special to the least special order. This technology will handle special exceptions before it is passed to a more common Catch Block.
  4. End with the word [Exception] as the exception class name. For example:
    Public class myfilenotfoundexception: applicationexception {}
  5. When creating a user-defined exception, you must ensure that the metadata of the exception can be used for remote code execution, including exceptions generated across application domains. For example, assume that application domain a creates application domain B that executes the code that throws an exception. In order for application domain a to properly capture and handle this exception, it must be able to locate the Assembly set that contains the exception thrown by application domain B. If application domain B throws an exception that is contained in the Assembly set under its application base, but not under the application base of application domain, application domain a will not be able to find this exception and will throw filenotfoundexception when running in the public language. To avoid this situation, you can deploy an Assembly set that contains exception information in two ways:
    1. Place the Assembly set on the basis of a public application shared by two application domains at the same time.

      -Or-

    2. If the domain does not share the basis of a public application, it will mark the Assembly set with a strong name to contain exception information and deploy the Assembly set to the Global Assembly Cache.
  6. In C # And C ++, at least three common constructors are used to create your own exception classes. For examples, refer to [Use user-defined exceptions].
  7. In most cases, you can use a predefined exception type. A new exception type is defined only when it is programmable. Introduce a new exception class to allow programmers to take other actions in the code based on this exception class.
  8. Most applications can derive custom exceptions from the exception class. This is the initial consideration that custom exceptions should be derived from the applicationexception class; however, it is not found that this will increase important value from habits.
  9. Each exception contains a localized description string. When you see an error message, this is the description string derived from the class to which an exception is thrown, better than from the exception class.
  10. Use Correct syntax error messages, including ending punctuation marks. Each sentence in the exception description string should end with a period.
  11. Provides the exception attribute for programmable access. Additional information about exceptions (except the description string) is included only when additional information is useful and programmable ).
  12. Returns NULL for very common errors. For example, file. Open returns NULL. If the file is not found, an exception is thrown if the file is found.
  13. The design never throws exceptions in general use. For example, a filestream class exposes other methods to check whether the file has reached the end. This avoids throwing an exception if you read it outside the end of the file. The following example shows how to read the end of a file.
    Class fileread {void open () {filestream stream = file. Open ("myfile.txt", filemode. Open); byte B; // readbyte returns-1 in EOF. While (B = stream. readbyte ())! = True) {// what to do. }}}
  14. An invalidoperationexception is thrown if an attribute set or method call does not properly provide the current state of the object.
  15. An argumentexception or a class derived from argumentexception is thrown if invalid parameters are passed.
  16. Stack tracing starts with the exception thrown statement and ends with the catch statement that captures the exception. You should understand this fact when deciding where to store a throw statement.
  17. The exception generator method is usually used for a class to throw the same common exception from different locations in its implementation. To avoid extra code, you can use the auxiliary method to create an exception and return it. For example:
    Class file {string filename; Public byte [] Read (INT bytes) {If (! Readfile (handle, bytes) Throw newfileioexception ();} fileexception newfileioexception () {string description = // create a localized string, including filename. Return new fileexception (description );}}

    Or use the constructor to create the exception. This is more suitable for global exception classes, such as argumentexception.

  18. Throw an exception to return the error code or hresult.
  19. Clear intermediate results when an exception is thrown. The caller should assume that there is no negative impact when an exception is thrown from the method.

Turn: http://www.cnblogs.com/Laeb/archive/2007/03/29/693253.html

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.