Unit 3: Exception Handling
Unit 3: Exception Handling
Handling
Unit 3
Ode to Errors, Bugs, and Exceptions
The Role of .NET Exception Handing,
The Simplest possible example
Throwing generic exceptions
Catching exceptions,
Configuring the state of an exception-Target Site
Stack trace, Helplink & data property
System Level Exception
Application-Level Exception
Prof. Sushant S.Sundikar Processing Multiple Exception
Generic catch statements,
Sahaj Computer Solutions
Rethrowing exception
9945323277 Inner exceptions
The Finally Block
0831-4200864 Who is throwing what?
The result of unhandled exceptions
www.sahajsolns.com Debugging Unhandled exceptions using VS. NET IDE.
Unit 3: Exception Handling 1
Bugs: This is, simply put, an error on the part of the programmer. For example, assume you are
programming with unmanaged C++. If you make calls on a NULL pointer or fail to delete allocated
memory (resulting in a memory leak), 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 track for while programming your application. Possible exceptions include attempting
to connect to a database that no longer exists, opening a corrupted file, or contacting a machine that
is currently offline. In each of these cases, the programmer (and end user) has little control over
these exceptional circumstances.
Program statements that you want to monitor for exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown. Your code can catch this exception using catch
and handle it in some rational manner. System-generated exceptions are automatically thrown by
the runtime system. To manually throw an exception, use the keyword throw. Any code that
absolutely must be executed upon exiting from a try block is put in a finally block.
try {
// Program: ch03pg01.cs
using System;
class ExcDemo1 {
try {
nums[i] = i;
catch (IndexOutOfRangeException) {
Console.WriteLine("Index out-of-bounds!");
using System;
class MultiCatchDemo {
int[] denom = { 2, 0, 4, 4, 0, 8 };
try {
numer[i]/denom[i]);
catch (DivideByZeroException) {
catch (IndexOutOfRangeException) {
catch {
// handle exceptions
For example:
try {
throw exceptOb;
Program ch03pg02.cs: Here is an example that illustrates the throw statement by manually
throwing a DivideByZeroException.
Rethrowing exception
An exception caught by one catch can be rethrown so that it can be caught by an outer catch. The
most likely reason for rethrowing an exception is to allow multiple handlers access to the exception.
To rethrow an exception, you simply specify throw, without specifying an expression. That is, you
use this form of throw:
throw;
Program ch03pg03.cs : The following program illustrates rethrowing an exception. In this case, it
rethrows an IndexOutOfRangeException.
By default, the value managed by the HelpLink property is an empty string. If you wish to fill this
property with an interesting value, you will need to do so before throwing the System.Exception
type.
For example:
// We need to call the HelpLink property, thus we need to create a local variable before throwing
the Exception object.
ex.HelpLink = "http://www.CarsRUs.com";
throw ex;
The catch logic could now be updated to print out this help link information as follows:
catch(Exception e)
// Various constructors.
Application-Level Exception
Given that all .NET exceptions are class types, you are free to create your own application-specific
exceptions. However, due to the fact that the System.SystemException base class represents
exceptions thrown from the CLR, you may naturally assume that you should derive your custom
exceptions from the System.Exception type. While you could do so, best practice dictates that you
instead derive from the System.ApplicationException type:
// Various constructors.
Inner exceptions
One try block can be nested within another. An exception generated within the inner try block that
is not caught by a catch associated with that try is propagated to the outer try block. For example,
here the IndexOutOfRangeException is not caught by the inner try block, but by the outer try:
using System;
class NestTrys {
int[] denom = { 2, 0, 4, 4, 0, 8 };
numer[i]/denom[i]);
catch (DivideByZeroException) {
catch (IndexOutOfRangeException) {
4 / 2 is 2
16 / 4 is 4
To specify a block of code to execute when a try/catch block is exited, include a finally block at the
end of a try/catch sequence. The general form of a try/catch that includes finally is shown here:
try {
finally {
// finally code
The finally block will be executed whenever execution leaves a try/catch block, no matter what
conditions cause it. That is, whether the try block ends normally, or because of an exception, the
last code executed is that defined by finally. The finally block is also executed if any code within
the try block or any of its catch blocks returns from the method .Here is an example of finally:
// Use finally.
using System;
class UseFinally
{
public static void GenException(int what)
{
int t;
int[] nums = new int[2];
Console.WriteLine("Receiving " + what);
try
{
switch(what)
{
case 0:
t = 10 / what; // generate div-by-zero error
break;
case 1:
nums[4] = 4; // generate array index error
break;
case 2:
return; // return from try block
}
}
catch (DivideByZeroException)
{
Console.WriteLine("Can't divide by Zero!");
return; // return from catch
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("No matching element found.");
}
finally {
Console.WriteLine("Leaving try.");
}
}
}
class FinallyDemo
{
static void Main()
{
for(int i=0; i < 3; i++)
{
UseFinally.GenException(i);
Console.WriteLine();
}
}
}
Receiving 0
Can't divide by Zero!
Leaving try.
Receiving 1
using System;
class NotHandled {
nums[i] = i;
When the array index error occurs, execution is halted and the following error message is displayed:
at NotHandled.Main()
Although such a message is useful while debugging, you would not want others to see it, to say the
least! This is why it is important for your program to handle exceptions itself.
To wrap things up, do be aware that Visual Studio 2005 provides a number of tools that help you
debug unhandled custom exceptions. If you were to start a debugging session (using the Debug Start
menu selection), Visual Studio automatically breaks at the time the uncaught exception is thrown.
Better yet, you are presented with a window (see Figure 3-1) displaying the value of the Message
property.