You are on page 1of 11

Exception Handling | 2020

An exception is a condition that is caused by runtime error in the program .When the c#
compiler encounter an error such as dividing an integer by zero, it create an exception
object and throw it(i.e. inform us that an error has occurred).
If the exception object is not caught and handled properly the compiler will
display an error message and will terminate the program.If you want the program to
continue with the execution of remaining code then we should try to catch the exception
object thrown by error condition and then display an appropriate message for taking
corrective actions.This task is known as exception handling.The error handling code
basically consist of two segment.
1) To detect error to throw exception.
2) Catch exception and take appropriate action.

Try and catch


C# uses a keyword try to prefer a block of code that is likely to causes an error condition
and throw that is likely to causes an error condition and throw an exception. A catch block
defined by the keyword ‘catch’ catches the exception thrown by try block and handle it
appropriately. The catch block is added immediately after the try block.

Syntax For this


try
{
Statements;
}
Catch(Exception e)
{
Statements;
}
The try block can have one or more statements that could generate an exception. If any one
statement generate an exception, the reaming statement that could generate an exception in
the same block are skipped and execution jumps to the catch block that is placed to the next
to try block. Note that catch stamen work single parameter which is reference to the
exception object thrown (by try block).If the catch parameter is match with the type of
exception object then the exception is caught and statements in the catch block will be

Pawar A.R. (Sangola College Sangola) 1


Exception Handling | 2020
executed otherwise the exception is not caught and the default exception handler will cause
the execution to terminate.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace demo_try
{
class Program
{
static void Main(string[] args)
{
int a, b, c, d;
a = 45;
b = 5;
c = 5;
try
{
d = (a / (b - c));
}
catch (DivideByZeroException e)
{

Console.WriteLine("Divide by zero Error");


}
d = (a / (b + c));
Console.WriteLine("The Value of d is" + d);
Console.ReadKey();
}
}
}

Multiple Catch Block


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace demo_mutiple_catch
{
class Program
{
static void Main(string[] args)
{
int a, b, c;
Console.WriteLine("Enter the 2 numbers");
try

Pawar A.R. (Sangola College Sangola) 2


Exception Handling | 2020
{
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = a / b;
Console.WriteLine("The value of c is " + c);
}
catch(DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
catch(FormatException e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();

}
}
}
It is possible to have more than one statements in the try block then there is possible to
generate multiple exception.
try
{
Statements;
}
Catch(Exception type1)
{
Statements;
}
Catch(Exception type2)
{
Statements;
}
Catch(Exception type n )
{
Statements;
}
When an exception in a try block is generated the c# treat the multiple catch statement
like cases in switch statements. The first statements whose parameter matches with
exception object will be executed and the remaining statements will be skipped.
Nested ‘try’ block
C# permit us nested try block inside program.
When nested try block are executed the exception that are thrown at various points are
handled as follows.
1) The point p1 are outside the inner try block.since any exception thrown at these
point will be handled by catch in outer block.The inner block simple ignored.

Pawar A.R. (Sangola College Sangola) 3


Exception Handling | 2020
2) Any exception thrown at point p1 will be handled by inner catch handler and
exception will continue at the next statement in the program.
3) If there is no suitable catch handler to catch an exception thrown at point p2,the
control will leave the inner block and look for a suitable one is found then that
handler is executed.
4) In case suitable catch handler is not found in inner block as well as outer block the
system will terminate the program abnormally.
try
{
---------------------
---------------------- Point P1
----------------------
try
{
----------------
----------------- Point P2
------------------
}
Catch(Exception type1 )
{
Statements;
}
Catch(Exception type2)
{
Statements;
}
}
Catch( )
{
Statements;
}
Catch( )
{
Statements;
}
---------------------
---------------------- Point P3
---------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace demo_nested_try
{
class Program
{

Pawar A.R. (Sangola College Sangola) 4


Exception Handling | 2020
static void Main(string[] args)
{
int a, b, c, d;
int []x = { 10, 5, 5 };
try
{
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = a / b;
Console.WriteLine("The value of c " + c);
try
{
d = x[0] / x[1];
Console.WriteLine("value of d is" + d);
}
catch(IndexOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
catch(FormatException e)
{
Console.WriteLine(e.Message);
}
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
catch(DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
int d1 = x[0] / (x[1] + x[2]);
Console.WriteLine("the value of d1 is " + d1);
Console.ReadKey();
}
}
}

Throw
It is possible to throw an exception manually by using throw statement. You can throw a
new exception nearly anywhere in c# code.It’s general form is
throw exception_object;
where exception object must be an object of an exception class derived from ‘Exception’.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Pawar A.R. (Sangola College Sangola) 5


Exception Handling | 2020
using System.Threading.Tasks;

namespace demo_throw
{
class Program
{
static void Main(string[] args)
{
int a, b, c;
a = 45;
b = 5;
try
{
c = a / b;
Console.WriteLine("The value of c is" + c);
throw new DivideByZeroException();
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);

}
Console.WriteLine("End");
Console.ReadKey();
}
}
}
Custom Exception
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace demo_cust_exce
{
class myexp: Exception
{
public myexp(string txt) :base(txt)
{

}
}
class demo
{
public void show()
{
int a, b, c;
a = 45;
b =5;

Pawar A.R. (Sangola College Sangola) 6


Exception Handling | 2020
try
{
Console.WriteLine(div(a, b));
}
catch(DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
}
public int div(int x,int y)
{
if (y==0)
{
myexp e = new myexp("denominator Can't be zero");
Console.WriteLine(e.Message);
}
return x / y;

}
}
class Program
{
static void Main(string[] args)
{
demo d = new demo();
d.show();
Console.ReadKey();
}
}
}
Finally
The purpose of finally statement is to ensure that the necessary cleanup of Object, usually
objects that are holding external resource happens immediately even if an exception is
thrown. One example of such cleanup is calling close a file (File stream) immediately after
use instead of waiting for the object to be garbage collector by CLR.
A database connection is another good example for being closed in finally
block. Because the number of connection allowed to database server is sometimes limited, it
is important to close database connection quickly as possible. If an exception is thrown
before you can close your connection this is another case where using the finally block is
preferable to waiting for garbage Collection.
In this example there is one invalid conversion statement that causes an exception
but the finally clause will executed and display the outputs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace demo finally

Pawar A.R. (Sangola College Sangola) 7


Exception Handling | 2020
{
class Program
{
static void Main(string[] args)
{
int i = 123;
string s = "Pune";
object o = s;
try
{
i = (int)o;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("The value of i " + i);
Console.WriteLine("Finally is execute");
}
Console.ReadKey();
}
}
}

Exception Hierarchy

In C#, all the exceptions are derived from the base class Exception which gets further
divided into two branches as ApplicationException and another one

Pawar A.R. (Sangola College Sangola) 8


Exception Handling | 2020
is SystemException. SystemException is a base class for all CLR or program code generated
errors. ApplicationException is a base class for all application related exceptions. All the
exception classes are directly or indirectly derived from the Exception class. In case
of ApplicationException, the user may create its own exception types and classes. But
SystemException contains all the known exception types such
as DivideByZeroException or NullReferenceException etc.

Different Exception Classes: There are different kinds of exceptions which can be
generated in C# program:
 Divide By Zero exception: It occurs when the user attempts to divide by zero
 Out of Memory exceptions: It occurs when then the program tries to use excessive
memory
 Index out of bound Exception: Accessing the array element or index which is not
present in it.
 Stackoverflow Exception: Mainly caused due to infinite recursion process
 Null Reference Exception : Occurs when the user attempts to reference an object
which is of NULL type.
…..and many more.

Exception Chain
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
one();
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
public static void one()
{
try
{
two();
}
catch (Exception e)
{
throw new Exception("First Exception", e);

Pawar A.R. (Sangola College Sangola) 9


Exception Handling | 2020
}
}
public static void two()
{
try
{
last();
}
catch (Exception e)
{
// Console.WriteLine("Third Exception",e);
throw new Exception("Second Exception", e);
}
}
public static void last()
{
throw new Exception("Last Exception");
}

}
}

Built-in Exception Classes

Exception Class Description

ArgumentException Raised when a non-null argument that is passed to a method is


invalid.

ArgumentNullException Raised when null argument is passed to a method.

ArgumentOutOfRangeException Raised when the value of an argument is outside the range of valid
values.

DivideByZeroException Raised when an integer value is divide by zero.

FileNotFoundException Raised when a physical file does not exist at the specified location.

FormatException Raised when a value is not in an appropriate format to be


converted from a string by a conversion method such as Parse.

IndexOutOfRangeException Raised when an array index is outside the lower or upper bounds
of an array or collection.

InvalidOperationException Raised when a method call is invalid in an object's current state.

KeyNotFoundException Raised when the specified key for accessing a member in a


collection is not exists.

NotSupportedException Raised when a method or operation is not supported.

Pawar A.R. (Sangola College Sangola) 10


Exception Handling | 2020
NullReferenceException Raised when program access members of null object.

OverflowException Raised when an arithmetic, casting, or conversion operation


results in an overflow.

OutOfMemoryException Raised when a program does not get enough memory to execute
the code.

StackOverflowException Raised when a stack in memory overflows.

TimeoutException The time interval allotted to an operation has expired.

The above table lists important built-in exception classes in .NET.

Pawar A.R. (Sangola College Sangola) 11

You might also like