Vous êtes sur la page 1sur 16

Exception Handling

Errors, Bugs and Exceptions

Bugs: These are, simply put, errors on the part of the programmer. For
example, assume you are programming with unmanaged C++. If you fail
to delete dynamically allocated memory, you have a bug.
User errors: Unlike bugs, user errors are typically caused by the
individual running your application, rather than by those who created it.
For example, an end user who enters a malformed string into a text box
could very well generate an error if you fail to handle this faulty input in
your code base.
Exceptions: Exceptions are typically regarded as runtime anomalies that
are difficult, if not impossible, to account for while programming your
application. Possible exceptions include attempting to connect to a
database that no longer exists, opening a corrupted file. In each of these
cases, the programmer (and end user) has little control over these
“exceptional” circumstances.
Exception Classes
System.SystemException:-
This class is for exceptions that are usually thrown by the .NET
runtime or that are considered to be of a generic nature and
might be thrown by almost any application.
Ex- ArgumentException, StackOverFlowException.

System.ApplicationException:-
This class is important, because it is the intended base for any
class of exception defined by third parties.
If you define any exceptions covering error conditions unique
to you application. You should derive these directly from
System.ApplicationException
Catching Exceptions

Devide the program into blocks of three different types


Try blocks encapsulate the code that forms the normal
operation of your program and that might encounter some
serious error conditions.

Catch Blocks encapsulate the code that deals with the various
error conditions that your code might have encountered by
working through any of the code in the accompanying try
block.

Finally blocks encapsulate the code that cleans up resources


Steps to trap error conditions

1. The excecution flow first enters the try block.


2. If no errors in the try block, execution proceeds
through the block, and when the end of try block is
reached, flow jumps to the finally block(if present). If
error occur execution jumps to catch block.
3. The error condition is handled in the catch block.
4. At the end of catch block, execution transfers to
finally block(if present)
5. The finally block is executed.
System.Exception Properties
Data This property retrieves a collection of key/value pairs (represented by an objec
implementing IDictionary) that provides additional,programmer-defined informatio
about the exception. By default, this collection is empty (e.g., null).
HelpLink This property returns a URL to a help file or website describing the
error in full detail.
InnerException This read-only property can be used to obtain information about th
previous exception(s) that caused the current exception to occur. The previou
exception(s) are recorded by passing them into the constructor of the most curren
exception.
Message This read-only property returns the textual description of a given error. Th
error message itself is set as a constructor parameter.
Source This property returns the name of the assembly that threw the exception.
StackTrace This read-only property contains a string that identifies the sequence o
calls that triggered the exception. As you might guess, this property is very usefu
during debugging or if you wish to dump the error to an external error log.
TargetSite This read-only property returns a MethodBase type, which describes
numerous details about the method that threw the exception
Syntax

try
{
//code for normal execution
}
catch
{
//error handling
}
finally
{
//cleanup
}
Processing Multiple Exceptions

When you are authoring multiple catch blocks, you


must be aware that when an exception is thrown, it will
be processed by the “first available” catch.

catch blocks are structured such that the very first


catch is the most specific exception (i.e., the most
derived type in an exception type inheritance chain),
leaving the final catch for the most general (i.e., the
base class of a given exception
inheritance chain, System.Exception).
Generic catch Statements
C# also supports a “generic” catch scope that does not explicitly
receive the exception object thrown by a given member:
static void Main(string[] args)
{
try
{
}
catch
{
Console.WriteLine("Something bad happened...");
}
}
Obviously, this is not the most informative way to handle exceptions,
given that you have no way to obtain meaningful data about the error that
occurred (such as the method name, call stack, or custom message).
Nevertheless, C# does allow for such a construct, which can be helpful
when you wish to handle all errors in a very generic fashion.
Rethrowing Exceptions
Be aware that it is permissible for logic in a try block to rethrow an
exception up the call stack to the previous caller. To do so, simply
make use of the throw keyword within a catch block. This passes the
exception up the chain of calling logic, which can be helpful if your
catch block is only able to partially handle the error at hand:

static void Main(string[] args)


{
try
{
}
catch(Exception e)
{
throw;
}
}
Inner Exceptions
When you encounter an exception while processing another
exception, best practice states that you should record the new
exception object as an “inner exception” within a new object of the
same type as the initial exception (that was a mouthful). The reason
we need to allocate a new object of the exception being handled is
that the only way to document an inner exception is via a constructor
parameter. Consider the following code:
catch (Exception e)
{
try
{
FileStream fs = File.Open(@"C:\carErrors.txt", FileMode.Open);

}
catch (Exception e2)
{
throw new CarIsDeadException(e.Message, e2);
}
}
Nested try Blocks
try
{
//point A
try{ //point B }
catch{ //point c}
finally{//clean up}
//point D
}
catch{//error handling}
finally{//clean up}
 If an exception is thrown inside the outer try block
but outside the inner try block(points A and D), the
situation is either the exception is caught by the outer
catch block and the outer finally block is executed.
If the excecution is thrown in the inner try block(point

b), and there is a suitable inner catch block to handle


exception, then inner finally block is executed before
execution resumes inside the outer try block.
There isn't suitable inner catch block to handle inner

exception, the inner finally block is executed and


search in outer catch block.
User-Defined Exceptions
If you want users to be able to programmatically distinguish between
some error conditions, you can create your own user-defined exceptions.
The .NET Framework provides a hierarchy of exception classes
ultimately derived from the base class Exception. Each of these classes
defines a specific exception, so in many cases you only have to catch the
exception. You can also create your own exception classes by deriving
from the Exception class.
When creating your own exceptions, it is good coding practice to end the
class name of the user-defined exception with the word "Exception." It is
also good practice to implement the three recommended common
constructors, as shown in the following example.
Example
using System;
public class EmployeeNotFoundException: Exception
{
public EmployeeNotFoundException()
{
}
public EmployeeNotFoundException(string message)
: base(message)
{
}

public EmployeeNotFoundException(string message, Exception inner)


: base(message, inner)
{
}
}
The Result of Unhandled Exceptions

Vous aimerez peut-être aussi