[go: up one dir, main page]

0% found this document useful (0 votes)
37 views9 pages

C# Exception

The document discusses exception handling in C#, explaining that exceptions are conditions caused by runtime errors, which can be caught and handled to prevent program termination. It outlines the structure of try-catch blocks, the use of multiple catch statements, and the finally statement for cleanup actions. Additionally, it covers nested try blocks and provides examples of common exceptions and their handling mechanisms.

Uploaded by

akshaya262021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views9 pages

C# Exception

The document discusses exception handling in C#, explaining that exceptions are conditions caused by runtime errors, which can be caught and handled to prevent program termination. It outlines the structure of try-catch blocks, the use of multiple catch statements, and the finally statement for cleanup actions. Additionally, it covers nested try blocks and provides examples of common exceptions and their handling mechanisms.

Uploaded by

akshaya262021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

18.

4 EXCEPTIONS ie Guhul a s uwnning


Anning
paogucm
An exception is a condition that is caused by a run-time error in the program. When the C#
compiler encounters
an error such as dividing an integer by zero, it creates an exception object and throws it (i.e., informs 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 we want the program to continue with the execution of the remaining code, then
we should try to catch the
exception object thrown by the error condition and then display an appropriate
message for taking corrective actions. This task is known as exception handling.)
The purpose of the exception handling mechanism is to
provide a means to detect and report an 'exceptional
circumstance' so that appropriate action can be taken. The mechanism
error handling code that performs the
suggests incorporation of a separate
following tasks:
Find the problem (Hit the exception)
Inform that an error has occurred (Throw the
exception)
Receive the error information (Catch the
exception)
Take corrective actions (Handle the
exception)
The error handling code
basically consists of two segments, one to detect errors and to throw exceptions
and the other to catch exceptions and to take
appropriate actions

ovdle a cua 1 bana Gohol honn o paut fo ouwtu o a Po


SJhuy AprplicahnExc eptio) - To caod Ou xon ertepionul ltut
Cctch
Analy
haod Managing Errors and Exceptions 347
auriting programs, we
must always be on the
Wheonerated.
uld
Some common
exceptions that we
lookout for places in the
program where an exception
must catch are listed in Table 18.1.
Table 18.1 Common C# exceptions
Exception Class
SyslemException
A failed Cause of Exception
run-time check; used as a base
ACcessException

Failure to acces_
class for other exceptions
a
type member, such
ArgumentException
An as a method or field
argument to a method was invalid
ArgumentNullException A null
ArqumentOutofRangeException
argument was passed toa method that does not
Argument value is out of range
accept it
AnthmeticException
Arithmetic over or
underflow
ArayTypeMismatchException has occurred
Attempt to store the wrong
BadimageFormatException type of object in an array
Image
is in the
wrong format
CoreException
Base class for
DivideByZeroException exceptions
thrown by the runtime
An
attempt
was made to divide
by
FomaltException zero
The format of an
ndexOutofRangeException argument is wrong
An array index is
out of bounds
InvalidCastException An attempt was
made to cast to
InvalidOperationException an invalid class
A method was
called at an invalid time
MissingMemberException An invalid version
of a DLL
NotFiniteNumberException A number is not
was accessed
valid
NotSupportedException Indicates that a method is not
NullReferenceException implemented by a class
Attempt to use an unassigned reference
OutofMemoryException Not enough
memory to continue execution
StackOverflowException A stack has
overflowed

18.5 SYNTAX OF
Ihe basic concepts of
EXCEPTION-HANDLING CODE
exception handling are throwing
an exception and catching it. This is ilustrated in
Fig. 18.1. try Block
Uses a keyword try to preface a block of code Statement that Exception object
Throws causes an exception creator
at is likely to cause an error condition and "thròw exception
eXception. A catch block
atch 'catches' the exception defined by the keyword object
'thrown'by the try block catch Block
handles it appropriately. The catch block is added Statements that Exception handler
mediately after the try block. The following example handle the exception
Ustrates the use of
simple try and catch statements.
Fig. 18.1 Exception-handling mechanism
try

statement; / generates an exception


348 Programming in C#

catch (Exception e)

statement; processes the exception

* ****

C Iy Dlock can have one or more statements that could generate an exception. If
If any
any one
generates an exception, the remaining statements in the block are skipped and execution jumns
emes
block that is placed next to the try block. Calr
n e catch block too can have one or more statements that are necessary to process the

Kemember that every try statement should be followed by at least one catch statement; otherwis
the eception
otherwise Complaafio
error will occur.
Note that the catch statement works like a method definition. Ine catch statement is Dasen.

arameter, which is the reference to the exception object thrown (oy tnie ty DiocK). If the catch Singi
matches withthetype of exception object,then the exception is caught and statements in the catch he
De executed. Otherwise, the exception is not caught and the default exception handler will cause the0ck
to terminate. executiro
Program 18.3 ilustrates-the use of try arnd catch blocks to handle an arithmetic exception. Note
modified version of Program 18.2. its
Program 18.3 Using try and catch for exception handling
using
System,name (puCt
class Error3 A1
publicstaticvoid Main()

inta 10;
int b 5;
int c 5
int x, y
try

X = a / (b-c); I Exception here

catch (Exception e)

Console.Writeline("Division by zero");

y =a/ (b+c);
Console.WritelLine("y = " + y);

The output of Program 18.3 is


Division by zero
y = 1
Managing Errors and Exceptions 349

the program did not stop at


that the point of
Nole

ondition. It catches the error Throw point


o l i o n a l

co condition, prints
TOr ssage and then continues the execution as if
Method that
as happened. Compare
this with the execution
of
causes an exception
18.2 which did not give the value of v.
natung.

Invoke
method
progaften, exceptions
Mo.
are thrown by methods that Try block
with
invoked from
from within the try blocks. The point at which Throw Invokes a method
gre
thrown is called the
tion is throw point. Once an exception that contains an error
n enis thrown to the catch
eXcepth
block, control cannot return
throw oint. This kind of relationship is
the shown in Catch block
18.2. Catches and handles
the exception

18.6 MULTIPLE CATCH STATEMENTS Fig. 18.2 Invoking a method that contain
n0Ssible to have more than one catch
e
statement in the exceptions
Catch block as illustrated below:

try

statement; I generates an exception


catch (Exception-Type-1 e)

statement processes exception type 1


catch (Exception-Type-2 e)

statement; II processes exception type 2

catch (Exception-type-N e)

statement; I processes exception type N

When an exception in a try block is generated, the C# treats the multiple catch statements like cases ina
Switch statement. The first statementwhose parametermatches with the exception object will be executed
and the remaining statements will be skipped.
Note that C# does not require any processing of the exception at all. We can simply have a catch statement
an empty block to avoid program abortion.
Wtn
Example:
catch (Exception e{}
This statement will catch an exception and then ignoreit
blocks
Program 18 4 Usng muliple catch

Pubic static votd Main( )

int []a = [5,10]:


nt b 5:
try

intx =a[2] b a[]:

catch(ArithmeticException e)

Console.WriteLine( "Division by zero");

catch(IndexOutOfRangeException e)

Console.WriteLine("Array index error");

catch(ArrayTypeMismatchException e)

Console.WritelLine("Wrong data type");

int y a[1]/a[0];
Console.Writeline("y = " + y);

and, when run, produces the following output:


Program 18.4 uses a chain of catch blocks
Array index error

y-2 does not exist because array


a is defined to have only two elements
ents, auam
Note that the array element a[2] the block
outside the array boundary thus causing
and a[1]. Therefore, the index 2 is
catch(IndexOutOfRangeException e)
The remaining catch blockS are skipped.
to catch and handle the error.
not catch any information about ne extepuUm

18.9 USING FINALLY STATEMENT


statement that can be used to handle an exception that
Supports another statement known as a finally be used to handle any exception
statements. A finally block can
not caught
by any of the previous catch
toy ate e i v t k ter fhelast
last atoh hte

na catch (

catch (.

finally Try block

* * * * ' * ° '

********

When a finally block is defined. the program is


guaranteed to execute, regardless of how control leaves Eror1 No errors
Error 2
the try, whether it is due to normal termination, due to
an exception occuring or due to a jump statement.
Figure 18.3 illustrates this. As a result, we can use it
Catch Catch
to perform certain housekeeping operations such as block1 block2
closing files and releasing system resourcés)
In Program 18.4, we may include the last two
statements inside a finally block as shown below.
hnally Finally
block

int y a[1]/a[0];
Console.Writeline("y = " +y);
Leaving try block

This will produce the same output. Fig. 18.3 Execution paths of try-catch-finally blocks

18.10 NESTED TRY BLOCKS


CH permits us to nest try blocks inside each other. Example:
try

(Point P1)

try
Exceptions 353
Managing Errors and

(Point P2)

catch
Inner
(Point P3) try block

finally

'
.(PointP4)
,

catch

finally

Forsimplicity, we have shown only one catch handleri each try block. However, we can string several
Catch handlers together
in each place
When nested try blocks are executed, the exceptions that are thrown at various points are handled as

follows
The points P1 and P4 are outside theinnertry block and therefore any exceptions thr at these
points will be handled by the catch in the outer block. The inner block is simply ignored
Any exception thrown at point P2 will be handled by the inner catch handler and the inner finally will
be executed The execution will continue at point P4 in the program.
If there is no suitable catch handler to catch an exception thrown at P2, the control will leave the inner
block (after executing the inner finally) and look for a suitable catch handler in the outer block. If a
suitable one is found, then that handler is executed followed by the outer finally code. Remember,
the code at point P4 will be skipped
If an exception is thrown at point P3, it is treated as if it had been thrown by the outer try block and,
therefore the control will immediately leave the inner block (of course, after executing the inner
and search for a suitable catch handler in the
outer block.
finally)
I n case, a suitable catch handler is not found, then the system will terminate program execution with

an appropriate message
rOgram 18.5 shows a simple implementation of nested try blocks. The program uses nested methods,

Sachhaving its own try.. catch blocks


throws an exception. Although the Division ( )
Main method invokes the Division( ) method which
of exception. The control is therefore transferred to the
methodhas a catch block, it es not match the type
catch handler. Itfinds one there and executes it.
OCK In Main and the program looks for a matching
hlocks
Program 18 5 nahested ny
e7ing

t
stat d Dision

int k= m/n:

catch (Argument Exception e)

Console.WritelLine("Caught an exception");

inally
Console.WriteLine("Inside Division Method");

public static void Main()

try

Divison (O;
catch (DivideByZeroException e)

Console. WritelLine("Caught an exception");


finally
Console.Write("Inside Main Method");

You might also like