As we all know, exception handling becomes a very
handy tool for debugging an application. Rajesh will now explein how
one should use Exceptions in C#.Exception
handling is an in built mechanism in .NET framework to detect and
handle run time errors. The .NET framework contains lots of standard
exceptions. The exceptions are anomalies that occur during the
execution of a program. They can be because of user, logic or system errors.
If a user (programmer) do not provide a mechanism to handle these
anomalies, the .NET run time environment provide a default mechanism,
which terminates the program execution.
C#
provides three keywords try, catch and finally to do exception
handling. The try encloses the statements that might throw an exception
whereas catch handles an exception if one exists. The finally can be
used for doing any clean up process.
The general form try-catch-finally in C# is shown below
try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}
If
any exception occurs inside the try block, the control transfers to the
appropriate catch block and later to the finally block.
But
in C#, both catch and finally blocks are optional. The try block can
exist either with one or more catch blocks or a finally block or with
both catch and finally blocks.
If
there is no exception occurred inside the try block, the control
directly transfers to finally block. We can say that the statements
inside the finally block is executed always. Note that it is an error
to transfer control out of a finally block by using break, continue,
return or goto.
In C#,
exceptions are nothing but objects of the type Exception. The Exception
is the ultimate base class for any exceptions in C#. The C# itself
provides couple of standard exceptions. Or even the user can create
their own exception classes, provided that this should inherit from
either Exception class or one of the standard derived classes of
Exception class like DivideByZeroExcpetion ot ArgumentException etc.
Uncaught Exceptions
The
following program will compile but will show an error during execution.
The division by zero is a runtime anomaly and program terminates with
an error message. Any uncaught exceptions in the current context
propagate to a higher context and looks for an appropriate catch block
to handle it. If it can
(
0)

(
0)