Best Practices for handling exceptions

Source: Internet
Author: User
Tags contains error code exception handling readfile stack trace domain
Well-designed error-handling block sets make programs more reliable and less prone to crashes because the application can handle such errors. The following table contains recommendations for best practices for handling exceptions:

Know when to set up Try/catch blocks. For example, you can programmatically examine the conditions that might occur without using exception handling. In other cases, it is appropriate to use exception handling to catch error conditions.
The following example uses an If statement to check whether a connection is closed. You can use this method instead of throwing an exception if the connection is not closed.

[Visual Basic]
If Conn. State <> connectionstate.closed Then
Conn. Close ()
End If
[C #]
IF (Conn. State!= connectionstate.closed)
Conn. Close ();
In the following example, an exception is thrown if the connection is not closed.

[Visual Basic]
Try
Conn. Close ()
Catch ex as InvalidOperationException
' Do something with the error or ignore it.
End Try
[C #]
try {
Conn. Close ();
}
catch (InvalidOperationException ex) {
Do something with the error or ignore it.
}
The method you choose depends on how often you expect the event to occur. If the event is indeed an exception and is an error (such as an unexpected end of a file), it is better to use exception handling because fewer code is normally executed. If the event is routine, it is better to use the programmatic method to check for errors. In this case, if an exception occurs, it will take a longer time to process.

Use try/finally blocks around code that can potentially generate exceptions, and set Catch statements in one place. In this way, the Try statement generates an exception, and the Finally statement closes or releases the resource, and the Catch statement handles the exception from the central location.
Always sort exceptions in Catch blocks in the most specific to the least specific order. This method handles the exception before it passes a specific exception to a more general Catch block.
Take the word "Exception" as the end of the exception class name. For example:
[Visual Basic]
Public Class EmployeeListNotFoundException
Inherits Exception
[C #]
public class Myfilenotfoundexception:applicationexception {
}
When you create a user-defined exception, you must ensure that the metadata for the exception is available to remotely executed code, including when an exception occurs across an application domain. For example, suppose application domain A creates application domain B, which executes the exception code thrown. Application domain A must be able to locate the assembly that contains the exception that is thrown by application domain B if it is to properly catch and handle the exception. If the assembly that contains the exception that is thrown by application domain B is located under the application base of application domain B, not the application base of application domain A, then application domain A cannot find an exception and the common language runtime throws a FileNotFoundException. To avoid this situation, you can deploy an assembly that contains exception information in two ways:
Place the assembly in a common application base shared by two application domains, or
If two application domains do not share a common application base, sign the assembly that contains the exception information with a strong name and deploy it to the global assembly cache.
When you create your own exception classes in C # and C + + Managed Extensions, you use at least three public constructors. For an example, see Using user-defined exceptions.
In most cases, the predefined exception types are used. New exception types are defined for programming scenarios only. The introduction of new exception classes enables programmers to take different actions in code based on exception classes.
Do not derive user-defined exceptions from the Exception base class. For most applications, derive custom exceptions from the ApplicationException class.
Contains a localized description string in each exception. When the user sees an error message, the information derives from the description string of the exception that was thrown, rather than from the exception class.
Use syntactically correct error messages, including closing punctuation. In the description string for the exception, each sentence should end with a period.
Provides Exception properties for programmatic access. Include additional information in the exception (excluding the description string) only if there is a programming scenario in which additional information is useful.
Returns null for a very common error condition. For example, if a file is not found, File.Open returns empty, but if the file is locked, an exception is thrown.
Class should be designed so that exceptions are never thrown in normal use. For example, the FileStream class exposes another method that determines whether the end of a file has been reached. This avoids the exception that is thrown when the end of the file is read. The following example shows how to read the end of a file.
[Visual Basic]
Class Fileread
Sub Open ()
Dim Stream as FileStream = File.Open ("MyFile.txt", FileMode.Open)
Dim B as Byte

' ReadByte returns-1 at EOF.
While B = stream. ReadByte () <> True
' Do something.
End While
End Sub
End Class
[C #]
Class Fileread {
void Open () {
FileStream stream = File.Open ("MyFile.txt", FileMode.Open);
BYTE B;

ReadByte returns-1 at EOF.
while (b = = stream. ReadByte ())!= true) {
Do something.
}
}
}
If the property set or method call is inappropriate based on the current state of the object, the InvalidOperationException is thrown.
Throws a ArgumentException or a class derived from ArgumentException if the wrong arguments are passed.
The stack trace starts at the statement that throws the exception, and ends with the catch statement that catches the exception. This should be considered when deciding where to place the Throw statement.
Use the Exception builder method. It is common for a class to throw the same exception from a different location in its implementation. To avoid excessive code, you should use the helper method to create the exception and return it. For example:
[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 ' Newfileioexception
End Class ' File
[C #]
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 the exception's constructor. This is more appropriate for global exception classes, such as ArgumentException.

Throws an exception instead of returning an 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.




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.