In simple terms Exceptions are errors. these are not the errors that are checked by any compiler. To be more simplistic any error which is not related to Syntax is called an Exception. Raising an exception is when an error occurs during the execution of a program forcing it to pause or break out.We have seen frequently that some new application or games when executing suddenly open a window and give you a message such as DirecteX missing or file missing or out of memory and most of these windows are followed by the application crashing or the application being shut down.
Thus as a programmer it is our duty to anticipate these kind of errors and make sure that the program exits gracefully.
DotNet has a basic Exception class which encompasses all kind of exceptions. This basic class has many child classes which represent specific exceptions. Difference being the parent class can represent every single exception but the child class can represent only specific type of exceptions. Below is a digram for all the exceptions present and their hierarchy.
+--System.Object
|
|
+--System.Exception
|
|
+--System.SystemException
|
|
+--System.ArgumentException
| |
| |
| +--System.ArgumentNullException
| |
| |
| +--System.ArgumentOutOfRangeException
| |
| |
| +--System.DuplicateWaitObjectException
|
|
+--System.ArithmeticException
| |
| |
| +--System.DivideByZeroException
| |
| |
| +--System.OverflowException
| |
| |
| +--System.NotFiniteNumberException
|
|
+--System.ArrayTypeMismatchException
|
|
+--System.ExecutionEngineException
|
|
+--System.FormatException
|
|
+--System.IndexOutOfRangeException
|
|
+--System.InvalidCastException
|
|
+--System.InvalidOperationException
| |
| |
| +--System.ObjectDisposedException
|
|
+--System.InvalidProgramException
|
|
+--System.IO.IOException
| |
| |
| +--System.IO.DirectoryNotFoundException
| |
| |
| +--System.IO.EndOfStreamException
| |
| |
| +--System.IO.FileLoadException
| |
| |
| +--System.IO.FileNotFoundException
| |
| |
| +--System.IO.PathTooLongException
|
|
+--System.NotImplementedException
|
|
+--System.NotSupportedException
|
|
+--System.NullReferenceException
|
|
+--System.OutOfMemoryException
|
|
+--System.RankException
|
|
+--System.Security.SecurityException
|
|
+--System.Security.VerificationException
|
|
+--System.StackOverflowException
|
|
+--System.Threading.SynchronizationLockException
|
|
+--System.Threading.ThreadAbortException
|
|
+--System.Threading.ThreadStateException
|
|
+--System.TypeInitializationException
|
|
+--System.UnauthorizedAccessException
Please do not be alarmed with so many entries, in a single program you will deal with 4-5 at most. Unless you are designing a software of the scale of MS-Office.
Two categories of exceptions exist under the base class Exception:
SystemException
Defines the base class for predefined exceptions in the System namespace.
This class is provided as a means to differentiate between exceptions defined by the system versus exceptions defined by applications.
SystemException does not provide information as to the cause of the Exception. In most scenarios, instances of this class should not be thrown. In cases where this class is instantiated, a human-readable message describing the error should be passed to the constructor.
SystemException is thrown by the common language runtime when errors occur that are nonfatal and recoverable by user programs. These errors result from failed runtime check (such as an array out-of-bound error), and can occur during the execution of any method. SystemException adds no new functionality to Exception.
SystemException uses the HRESULT COR_E_SYSTEM, that has the value 0x80131501.
ApplicationException
The exception that is thrown when a non-fatal application error occurs.
User applications, not the common language runtime, throw custom exceptions derived from the ApplicationException class. The ApplicationException class differentiates between exceptions defined by applications versus exceptions defined by the system.
If you are designing an application that needs to create its own exceptions, you are advised to derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value.ApplicationException uses the HRESULT COR_E_APPLICATION, which has the value 0x80131600.
Handling Exceptions
Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code.
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
Thus as a programmer it is our duty to anticipate these kind of errors and make sure that the program exits gracefully.
DotNet has a basic Exception class which encompasses all kind of exceptions. This basic class has many child classes which represent specific exceptions. Difference being the parent class can represent every single exception but the child class can represent only specific type of exceptions. Below is a digram for all the exceptions present and their hierarchy.
+--System.Object
|
|
+--System.Exception
|
|
+--System.SystemException
|
|
+--System.ArgumentException
| |
| |
| +--System.ArgumentNullException
| |
| |
| +--System.ArgumentOutOfRangeException
| |
| |
| +--System.DuplicateWaitObjectException
|
|
+--System.ArithmeticException
| |
| |
| +--System.DivideByZeroException
| |
| |
| +--System.OverflowException
| |
| |
| +--System.NotFiniteNumberException
|
|
+--System.ArrayTypeMismatchException
|
|
+--System.ExecutionEngineException
|
|
+--System.FormatException
|
|
+--System.IndexOutOfRangeException
|
|
+--System.InvalidCastException
|
|
+--System.InvalidOperationException
| |
| |
| +--System.ObjectDisposedException
|
|
+--System.InvalidProgramException
|
|
+--System.IO.IOException
| |
| |
| +--System.IO.DirectoryNotFoundException
| |
| |
| +--System.IO.EndOfStreamException
| |
| |
| +--System.IO.FileLoadException
| |
| |
| +--System.IO.FileNotFoundException
| |
| |
| +--System.IO.PathTooLongException
|
|
+--System.NotImplementedException
|
|
+--System.NotSupportedException
|
|
+--System.NullReferenceException
|
|
+--System.OutOfMemoryException
|
|
+--System.RankException
|
|
+--System.Security.SecurityException
|
|
+--System.Security.VerificationException
|
|
+--System.StackOverflowException
|
|
+--System.Threading.SynchronizationLockException
|
|
+--System.Threading.ThreadAbortException
|
|
+--System.Threading.ThreadStateException
|
|
+--System.TypeInitializationException
|
|
+--System.UnauthorizedAccessException
Please do not be alarmed with so many entries, in a single program you will deal with 4-5 at most. Unless you are designing a software of the scale of MS-Office.
Two categories of exceptions exist under the base class Exception:
- The pre-defined common language runtime exception classes derived from SystemException.
- The user-defined application exception classes derived from ApplicationException.
SystemException
Defines the base class for predefined exceptions in the System namespace.
This class is provided as a means to differentiate between exceptions defined by the system versus exceptions defined by applications.
SystemException does not provide information as to the cause of the Exception. In most scenarios, instances of this class should not be thrown. In cases where this class is instantiated, a human-readable message describing the error should be passed to the constructor.
SystemException is thrown by the common language runtime when errors occur that are nonfatal and recoverable by user programs. These errors result from failed runtime check (such as an array out-of-bound error), and can occur during the execution of any method. SystemException adds no new functionality to Exception.
SystemException uses the HRESULT COR_E_SYSTEM, that has the value 0x80131501.
ApplicationException
The exception that is thrown when a non-fatal application error occurs.
User applications, not the common language runtime, throw custom exceptions derived from the ApplicationException class. The ApplicationException class differentiates between exceptions defined by applications versus exceptions defined by the system.
If you are designing an application that needs to create its own exceptions, you are advised to derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value.ApplicationException uses the HRESULT COR_E_APPLICATION, which has the value 0x80131600.
Handling Exceptions
Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code.
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
Term | Definition |
tryStatements | Optional. Statement(s) where an error can occur. Can be a compound statement. |
Catch | Optional. Multiple Catch blocks permitted. If an exception occurs when processing the Try block, each Catch statement is examined in textual order to determine whether it handles the exception, with exception representing the exception that has been thrown. |
exception | Optional. Any variable name. The initial value of exception is the value of the thrown error. Used with Catch to specify the error caught. If omitted, the Catch statement catches any exception. |
type | Optional. Specifies the type of class filter. If the value of exception is of the type specified by type or of a derived type, the identifier becomes bound to the exception object. |
When | Optional. A Catch statement with a When clause catches exceptions only when expression evaluates to True. A When clause is applied only after checking the type of the exception, and expression may refer to the identifier representing the exception. |
expression | Optional. Must be implicitly convertible to Boolean. Any expression that describes a generic filter. Typically used to filter by error number. Used with When keyword to specify circumstances under which the error is caught. |
catchStatements | Optional. Statement(s) to handle errors that occur in the associated Try block. Can be a compound statement. |
Exit Try | Optional. Keyword that breaks out of the Try...Catch...Finally structure. Execution resumes with the code immediately following the End Try statement. The Finally statement will still be executed. Not allowed in Finally blocks. |
Finally | Optional. A Finally block is always executed when execution leaves any part of the Try statement. |
finallyStatements | Optional. Statement(s) that are executed after all other error processing has occurred. |
End Try | Terminates the Try...Catch...Finally structure. |
If you anticipate that a particular exception might occur during a particular section of code, put the code in a Try block and use a Catch block to retain control and handle the exception if it occurs. You can use as many different Catch blocks as necessary within a Try structure.
Local variables from a Try block are not available in a Catch block because they are separate blocks. If you want to use a variable in more than one block, declare the variable outside the Try...Catch...Finally structure.
The Try block contains code where an error can occur, and the Catch block contains code to handle any error that does occur. If an error occurs in the Try block, program control is passed to the appropriate Catch statement for disposition. The exception argument is an instance of the Exception class or a class that derives from the Exception class. The Exception class instance corresponds to the error that occurred in the Try block. The instance contains information about the error. This includes, among other things, its number and message.
If a Catch statement does not specify an exception argument, it catches any kind of system or application exception. You should always use this variation as the last Catch block in the Try...Catch...Finally structure, after catching all the specific exceptions you anticipate. Control flow can never reach a Catch block that follows a Catch without an exception argument.
If you have one or more statements that must run before you exit the Try structure, use a Finally block. Control passes to the Finally block just before it passes out of the Try structure. This is true even if an exception occurs anywhere inside the Try structure.
Control does not pass from a Try or Catch block to the corresponding Finally block in the following cases:
- An End Statement is encountered within the Try or Catch block.
- A StackOverflowException is thrown within the Try or Catch block.
Public Sub TryExample() Dim x As Integer = 5 ' Declare variables. Dim y As Integer = 0 Try ' Set up structured error handling. x = x \ y ' Cause a "Divide by Zero" error. Catch ex As Exception When y = 0 ' Catch the error. Beep() MsgBox("You tried to divide by 0.") ' Show an explanatory message. Finally Beep() ' This line is executed no matter what. End Try End Sub
Do not handle errors by catching non-specific exceptions, such as System.Exception, System.SystemException, and so on, in framework code.
Avoid handling errors by catching non-specific exceptions, such as System.Exception, System.SystemException, and so on, in application code. There are cases when handling errors in applications is acceptable, but such cases are rare.
An application should not handle exceptions that can result in an unexpected or exploitable state. If you cannot predict all possible causes of an exception and ensure that malicious code cannot exploit the resulting application state, you should allow the application to terminate instead of handling the exception.
Do not exclude any special exceptions when catching for the purpose of transferring exceptions.
Instead of creating lists of special exceptions in your catch clauses, you should catch only those exceptions that you can legitimately handle. Exceptions that you cannot handle should not be treated as special cases special-cased in non-specific exception handlers. The following code example demonstrates incorrectly testing for special exceptions for the purposes of re-throwing them.
Consider catching specific exceptions when you understand why it will be thrown in a given context.
You should catch only those exceptions that you can recover from. For example, a FileNotFoundException that results from an attempt to open a non-existent file can be handled by an application because it can communicate the problem to the user and allow the user to specify a different file name or create the file. A request to open a file that generates anExecutionEngineException should not be handled because the underlying cause of the exception cannot be known with any degree of certainty, and the application cannot ensure that it is safe to continue executing.
Do not overuse catch. Exceptions should often be allowed to propagate up the call stack.
Do not handle non-CLS-compliant exceptions (exceptions that do not derive from System.Exception) using a parameterless catch block. Languages that support exceptions that are not derived from Exception are free to handle these non-CLS compliant exceptions.
Consider catching specific exceptions when you understand why it will be thrown in a given context.
You should catch only those exceptions that you can recover from. For example, a FileNotFoundException that results from an attempt to open a non-existent file can be handled by an application because it can communicate the problem to the user and allow the user to specify a different file name or create the file. A request to open a file that generates anExecutionEngineException should not be handled because the underlying cause of the exception cannot be known with any degree of certainty, and the application cannot ensure that it is safe to continue executing.
Do not overuse catch. Exceptions should often be allowed to propagate up the call stack.
Catching exceptions that you cannot legitimately handle hides critical debugging information.
Do use try-finally and avoid using try-catch for cleanup code. In well-written exception code, try-finally is far more common than try-catch.
Do use try-finally and avoid using try-catch for cleanup code. In well-written exception code, try-finally is far more common than try-catch.
The purpose of a catch clause is to allow you to handle exceptions (for example, by logging a non-fatal error). The purpose of a finally clause is to allow you to execute cleanup code regardless of whether an exception was thrown. If you allocate expensive or limited resources such as database connections or streams, you should put the code to release them inside afinally block.
Do prefer using an empty throw when catching and re-throwing an exception. This is the best way to preserve the exception call stack.
Do prefer using an empty throw when catching and re-throwing an exception. This is the best way to preserve the exception call stack.
Do not handle non-CLS-compliant exceptions (exceptions that do not derive from System.Exception) using a parameterless catch block. Languages that support exceptions that are not derived from Exception are free to handle these non-CLS compliant exceptions.
No comments:
Post a Comment