Sei sulla pagina 1di 9

Exception Handling

What Are Exceptions


The C# language's exception handling features provide a way to deal with any unexpected or
exceptional situations that arise while a program is running. Exception handling uses the try,
catch, and finally keywords to attempt actions that may not succeed, to handle failures, and to
clean up resources afterwards. Exceptions can be generated by the common language runtime
(CLR), by third-party libraries, or by the application code using the throw keyword.
In this example, a method tests for a division by zero, and catches the error. Without the
exception handling, this program would terminate with a DivideByZeroException was
unhandled error.
int SafeDivision(int x, int y)
{
try
{
return (x / y);
}
catch (System.DivideByZeroException dbz)
{
System.Console.WriteLine("Division by zero attempted!");
return 0;
}
}

Exceptions have the following properties:

When your application encounters an exceptional circumstance, such as a division by


zero or low memory warning, an exception is generated.

Use a try block around the statements that might throw exceptions.

Once an exception occurs within the try block, the flow of control immediately jumps to
an associated exception handler, if one is present.

If no exception handler for a given exception is present, the program stops executing with
an error message.

If a catch block defines an exception variable, you can use it to get more information on
the type of exception that occurred.

Actions that may result in an exception are executed with the try keyword.

An exception handler is a block of code that is executed when an exception occurs. In C#,
the catch keyword is used to define an exception handler.

Exceptions can be explicitly generated by a program using the throw keyword.

Exception objects contain detailed information about the error, including the state of the
call stack and a text description of the error.

Code in a finally block is executed even if an exception is thrown, thus allowing a


program to release resources.

Exception Handling
Error (bug)
It is a Mistake done by user or System
Types of Errors
=>Build Errors (Compile Time)
=>Exceptions (Runtime Time)
Build Errors
These can occur at Compile time. These can be Handled by developer .If the program does not
have any build errors then .exe will be generated.
Exceptions
These are the Runtime Errors. These will terminate the Program abnormally. These can be
handled by Exception Manager of CLR.

Try, Catch, Finally blocks:


Try block
A try block is used by C# programmers to partition code that may be affected by an exception,
and catch blocks are used to handle any resulting exceptions. A finally block can be used to
execute code regardless of whether an exception is thrown which is sometimes necessary, as

code following a try/catch construct will not be executed if an exception is thrown. A try block
must be used with either a catch or a finally block, and can include multiple catch blocks. For
example:

try
{
// Code to try here.
}
catch (System.Exception ex)
{
// Code to handle exception here.
}
try
{
// Code to try here.
}
finally
{
// Code to execute after try here.
}

try
{

// Code to try here.


}
catch (System.Exception ex)
{
// Code to handle exception here.
}
finally
{
// Code to execute after try (and possibly catch) here.
}

A try statement without a catch or finally block will result in a compiler error.
Catch block:
A catch block can specify an exception type to catch. This type is called an exception filter, and must
either be the Exception type, or derived from this type. Application-defined exceptions should derive
from ApplicationException.

Multiple catch blocks with different exception filters can be chained together. Multiple catch blocks are
evaluated from top to bottom, but only one catch block is executed for each exception thrown. The first
catch block that species the exact type or a base class of the thrown exception will be executed. If no
catch block specifies a matching exception filter, then a catch block with no filter (if any) will be
executed. It is important to place catch blocks with the most specific most derived exception
classes first.
You should catch exceptions when:

You have a specific understanding of why the exception was thrown, and can implement a
specific recovery, such as catching a FileNotFoundException object and prompting the user to
enter a new file name.
You can create and throw a new, more specific exception. For example :

int GetInt(int[] array, int index)


{

try
{

return array[index];
}
catch(System.IndexOutOfRangeException e)
{
throw new System.ArgumentOutOfRangeException(
"Parameter index is out of range.");
}
}

To partially handle an exception. For example, a catch block could be used to add an entry to an
error log, but then re-throw the exception to allow subsequent handling to the exception. For
example:
try
{
// try to access a resource
}
catch (System.UnauthorizedAccessException e)
{
LogError(e); // call a custom error logging procedure
throw e;
// re-throw the error
}

Finally block:

A finally block allows clean-up of actions performed in a try block. If present, the finally block
executes after the try and catch blocks execute. A finally block is always executed, regardless of
whether an exception is thrown or whether a catch block matching the exception type is found.
The finally block can be used to release resources such as file streams, database connections, and
graphics handles without waiting for the garbage collector in the runtime to finalize the objects.
See using Statement (C# Reference) for more information.
In this example, the finally block is used to close a file opened in the try block. Notice that the
state of the file handle is checked before it is closed. If the try block failed to open the file, the
file handle will still be set to null. Alternatively, if the file is opened successfully and no
exception is thrown, the finally block will still be executed and will close the open file.
System.IO.FileStream file = null;
System.IO.FileInfo fileinfo = new System.IO.FileInfo("C:\\file.txt");
try
{
file = fileinfo.OpenWrite();
file.WriteByte(0xF);
}
finally
{
// check for null because OpenWrite
// might have failed
if (file != null)
{
file.Close();
}
}

Custom Exceptions
Introduction
Enhanced Exception Handling is one of key features that is most prominently available in
.Net both 2003 version and Whidbey versions of C#.
This paper discusses the implementation of Custom Exception Handling using the existing
features of C# .Net.
The Concept
The whole idea of having customized Exception Handling is centered around the fact that
there needs to be a generic approach of catching and throwing Exceptions.
For implementing custom Exception Handling we need to derive the class CustomException
from the system base class ApplicationException. In general, for customizing Exception
Handling the following components are necessary:

1.

A custom exception class which would host the exception thrown and can be thrown
as a new exception.

2.

A message class that would host all user - friendly Application messages that need to
be displayed.

Implementation
The following are the steps that are required to implement custom exception for creation of
the above mentioned components:
Step 1:
Define a project called Enumerators that would contain the definitions of all the Enumerators
as the following:
using System;
namespace CustomException
{
/// <summary>
/// Severity level of Exception
/// </summary>
public enum SeverityLevel
{
Fatal,
Critical,
Information
}
/// <summary>
/// Log level of Exception
/// </summary>
public enum LogLevel
{
Debug,
Event
}
}
1.

The Severity level determines the criticality of the error.

2.

The Loglevel determines whether an entry needs to be made in Log. Based on the
log level chosen , entries can be made either in the Debug Log or System Event Log .

Step 2:
Add another project named CustomException. Add a reference of the Enumerators project.
To the project add the following class deriving from ApplicationException:
using System;
namespace CustomException
{

/// <summary>
/// Summary description for CustomException
/// </summary>
public class CustomException : ApplicationException
{
// private members
// defines the severity level of the Exception
private SeverityLevel severityLevelOfException ;
// defines the logLevel of the Exception
private LogLevel logLevelOfException ;
// System Exception that is thrown
private Exception innerException ;
// Custom Message
private string customMessage ;
/// <summary>
/// Public accessor of customMessage
/// </summary>
public string CustomMessage
{
get {return this.customMessage; }
set {this.customMessage = value; }
}
/// <summary>
/// Standard default Constructor
/// </summary>
public CustomException( )
{}
/// <summary>
/// Constructor with parameters
/// </summary>
/// <param name="severityLevel"></param>
/// <param name="logLevel"></param>
/// <param name="exception"></param>
/// <param name="customMessage"></param>
public CustomException( SeverityLevel severityLevel , LogLevel logLevel, Exception
exception, string customMessage)
{
this.severityLevelOfException = severityLevel ;
this.logLevelOfException = logLevel ;
this.innerException = exception ;
this.customMessage = customMessage ;
}
}
}
One advantage of creating a custom Exception class is that the Constructor can be enabled
to writing to a Log on instantiation of the CustomException Object using TraceListeners. The
entry to the log would be based on the logLevel. This would force - write an entry each time
the custom Exception is thrown.
Thus we have a customException which could be thrown in the catch - handlers of system defined exceptions.

Step 3:
For implementing the CustomMessage component , create an Exception.resx File that would
host the error string and the corresponding message string as key-value pair.
Ex. "Test", "Testing Error"
Step 4:
Add to project a CustomMessage.cs class File. This File would look in the following way:
using System.Threading;
using System.Resources;
using System.Reflection;
namespace CustomException
{
/// <summary>
/// Summary description for CustomMessage.
/// </summary>
public class CustomMessage
{
public CustomMessage()
{
}
public string GetString(string key)
{
// Create a resource manager to retrieve resources.
ResourceManager rm = new ResourceManager("Exceptions",
Assembly.GetExecutingAssembly());
// Get the culture of the currently executing thread.
// The value of ci will determine the culture of
// the resources that the resource manager retrieves.
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
// Retrieve the value of the string resource and return it
String str = rm.GetString(key, ci);
return str ;
}
}
}
The GetString() of the CustomMessage class is used to retrieve the value string
corresponding to the key passed as parameter from the Exceptions resource File.
Usage
a) Add to existing Solution a Test Windows Applications Project.
b) Add the References to both the CustomException and the Enumerators projects.
c) Write a function which would throw a system exception , encapsulated in a try-catch
block as follows :

private void Updater()


{
try
{
int i = 0;
int j = 8 ;
int k= j/i;
}
catch(Exception ex)
{
SeverityLevel severityLevel = SeverityLevel.Critical;
LogLevel logLevel = LogLevel.Debug;
CustomMessage customMessage = new CustomMessage();
throw new
CustomException.CustomException( severityLevel,logLevel,ex.InnerException,customMessag
e.GetString("Test"));
}
}
d) In the Catch Block , re-throw the Exception as a CustomException
e) On a button_click event handler add the following code :
private void buttonTest_Click(object sender, System.EventArgs e)
{
try
{
this.Updater();
}
catch(CustomException.CustomException ce)
{
MessageBox.Show(ce.CustomMessage);
}
}
Conclusion
The above is one of the several methods of implementing Custom Exceptions in C#. Another
method would be using Application Blocks. Yet another method would be specifically
defining all the Application Exceptions as separate classes and using them

Potrebbero piacerti anche