Best practices for Exception Handling

Source: Internet
Author: User
A well-designed code block set of error processing makes the program more reliable and not prone to crashes, as the application can handle such errors. The following table provides suggestions on best practices for exception handling:

  • Know when to set Try/Catch blocks. For example, you can check possible conditions programmatically without exception handling. In other cases, exception handling is appropriate to capture error conditions.

    The following example uses the if statement to check whether the connection is closed. If the connection is not closed, you can use this method instead of triggering an exception.

    Copy code in Visual Basic
    If conn.State <> ConnectionState.Closed Then      conn.Close()   End If
    C # copy code
    if(conn.State != ConnectionState.Closed)      conn.Close();

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

    Copy code in Visual Basic
    Try      conn.Close()   Catch ex As InvalidOperationException      'Do something with the error or ignore it.   End Try
    C # copy code
    try {     conn.Close();   }   catch(InvalidOperationException ex) {     //Do something with the error or ignore it.   }

    The method selected depends on the frequency of the expected event. If the event is indeed abnormal and is an error (like the end of an external file), it is better to use Exception Processing, because less code is executed under normal circumstances. If an event occurs routinely, it is better to use programming methods to check errors. In this case, if an exception occurs, it will take a longer time to process it.

  • Use Try/Finally blocks around codes that may generate exceptions, and place Catch statements in one place. In this way, the Try statement generates an exception. The Finally statement closes or releases the resource, while the Catch statement handles the exception from the center.

  • Always sort exceptions in Catch blocks in the most specific to the least specific order. This method handles a specific exception before passing it to a more general Catch Block.

  • End with the word "Exception" as the Exception class name. For example:

    Copy code in Visual Basic
    Public Class EmployeeListNotFoundException    Inherits Exception
    C # copy code
    public class MyFileNotFoundException : Exception {}
  • When creating a user-defined exception, you must ensure that the exception metadata is available for code remotely executed, including when an exception occurs across application domains. For example, if application domain A creates application domain B, the latter executes the Exception Code. If application domain A wants to correctly capture and handle exceptions, it must be able to locate the Assembly containing exceptions thrown by application domain B. If the Assembly containing exceptions caused by application domain B is located in the application base Directory of application domain B, rather than in the application base Directory of application domain, application domain A will not be able to find the exception, and the public language runtime will cause FileNotFoundException. To avoid this situation, you can deploy an assembly containing exception information in two ways:

    • Place the assembly in a public application base shared by two application domains

      -Or-

    • If two application domains do not share a public application base, use a strong name to sign the Assembly containing the exception information and deploy it to the global assembly cache.

  • When creating your own exception classes in C # And C ++, you must use at least three common constructors. For examples, see How to: create a user-defined exception.

  • In most cases, use the predefined exception type. Define new exception types only for programming solutions. Introduce new exception classes so that programmers can perform different operations in the code based on the exception classes.

  • For most applications, custom exceptions are derived from the Exception class. The user-defined exception was originally required to be derived from the ApplicationException class, but it was not found to be of great significance in practice.

  • Each exception contains a localized description string. When an error message is displayed, the information is derived from the description string of the exception, rather than from the exception class.

  • Use the correct syntax error message (including ending punctuation marks ). In the exception description string, each sentence should end with a full stop.

  • Provides the Exception attribute for programming access. An exception contains additional information (not a description string) only when there is a useful programming scheme for additional information ).

  • Return null for very common errors. For example, if the file is not found, Open returns null, but if the file is locked, an exception is thrown.

  • Class design should avoid exceptions during normal use. For example, the FileStream class exposes another method to determine whether the object has reached the end. This avoids the exception caused by reading more than the end of the file. The following example shows how to read the end of a file.

    Copy code in Visual Basic
    Class FileRead    Public Sub Open(ByVal fileToRead As FileStream)        ' This If statement is optional        ' as it is very unlikely that        ' the stream would ever be null        If IsDBNull(fileToRead) Then            Throw New System.ArgumentNullException()        End If        Dim b As Integer        ' Set the stream position to the beginning of the file.        fileToRead.Seek(0, SeekOrigin.Begin)        ' Read each byte to the end of the file.        For i As Integer = 0 To fileToRead.Length            b = fileToRead.ReadByte()            Console.Write(b.ToString())            ' Or do something else with the byte.        Next    End SubEnd Classclass FileRead {    public void Open(FileStream fileToRead)     {        // This if statement is optional        // as it is very unlikely that        // the stream would ever be null.        if (fileToRead == null)        {            throw new System.ArgumentNullException();        }        int b;        // Set the stream position to the beginning of the file.        fileToRead.Seek(0, SeekOrigin.Begin);        // Read each byte to the end of the file.        for (int i = 0; i < fileToRead.Length; i++)        {            b = fileToRead.ReadByte();            Console.Write(b.ToString());            // Or do something else with the byte.        }    }}
  • If the property set or method call is inappropriate based on the current state of the object, InvalidOperationException is thrown.

  • If the passed parameter is invalid, ArgumentException or a class derived from ArgumentException is triggered.

  • Stack tracing starts from the statement that causes an exception and ends with the Catch statement that captures the exception. Consider this when deciding where to place the Throw statement.

  • Use the exception generator method. It is common for a class to cause the same exception from different locations in its implementation. To avoid excessive code, use the Helper method to create an exception and return it. For example:

    Copy code in Visual Basic
    Class File   Private fileName As String      Public Function Read(bytes As Integer) As Byte()      If Not ReadFile(handle, bytes) Then         Throw NewFileIOException()      End If   End Function 'Read      Function NewFileIOException() As FileException      Dim description As String = __unknown ' Build localized string, including fileName.      Return New FileException(description) '   End Function 'NewFileIOExceptionEnd Class 'File
    C # copy code
    class File {    string fileName;    public byte[] Read(int bytes) {        if (!ReadFile(handle, bytes))            throw NewFileIOException();    }    FileException NewFileIOException() {        string description = // Build localized string, including fileName.        return new FileException(description);     }}

    Alternatively, an exception is generated using an abnormal constructor. This is more suitable for global exception classes, such as ArgumentException.

  • Raise an exception instead of returning the error code or HRESULT.

  • Clears intermediate results when an exception is thrown. When an exception is thrown from a method, the caller should be able to assume that there are no side effects.

Related Article

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: [email protected] 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.