Exception Handlings in .net..?


In this article I'm trying to explain what are the exceptions and different types of exceptions and working with multiple catch blocks and working with try catch and finally blocks with small small examples. And discussing with User Defined exceptions and system exceptions.

Exception Handlings:


In this article I'm trying to explain what are the exceptions and types of exceptions and working with multiple catch blocks and working with try catch and finally blocks with small small examples.

As we have learnt that when ever an exception occurs our program terminates abnormally with out the next lines of code, even if the next lines of code is not related to exception. so if we can stop the abnormal termination of program we can make the statements which are not related with the exceptions to execute.
If we want to handle an exception our code should be enclosed under some special blocks.
i.e. try, catch block which has to be used as following.

Try, Catch Blocks:



Try
{
-statements which will cause an exception
-statements which doesn't require exception when exception occurs.
}
-------multiple catch blocks.


When the code is enclosed under try and catch blocks the execution of program takes place the following.
If all the statements in try are executed successfully from the last statement of try the control directly jumps the first statement which is present after catch block without executing any catch block.
If any statement in try faces (or) comes across an exception from that line the control directly jumps to the catch blocks checking for a matching catch block. If a matching block is available abnormal termination stops there executes the code under the catch block and then jumps to the first statement after catch block.
If matching catching block is not available the abnormal termination occurs again.
EX: Add a class Demo.cs

Class Demo
{
Static void main()
{
int x, y, z;
try
{
Console.WriteLine ("enter x value");
x=int.Parse(Console.WriteLine());
Console.Write("enter y value");
Z=x/y;
Console.WriteLine (z);
}
Catch (Divison by zero Exception ex)
{
Console.WriteLine ("divisor can't zero");
}
Catch (FormatException ex)
{
Console.WriteLine ("input must be integer");
}
Catch (Exception ex)
{
Console.WriteLine ("Error occurred");
}
}
}


Finally Block:



This is another block of code which can be paired with try and catch.
The specialty of this block is it executes both when an exception occurred
or did not occurs also.

EX:

Add a class Finaldemo.cs


Class Finaldemo
{
Static void main()
{
int x,y,z;
try
{
Console.Write("enter x value");
x=int.Parse(Console.WriteLine());
Console.Write("enter x value");
x=int.Parse(Console.WriteLine ());
if(y==1)
return;
z=x/y;
Console.WriteLine (z);
}
Catch(Exception ex)
{
Console.WriteLine (ex.message());
}
finally
{
Console.WriteLine ("Final block");
}
Console.WriteLine ("end of the program");
}
}


In the above program if the value to the divisor is gives as one the exception of program steps because return statement will jump to control out of the method. But all this happen only after execution of finally block. Because once control enters into try without executing finally we can't stop the execution of a program.

Message is a virtual property of exception class which returns the error message. i.e. associated with currently occurred exception.
As message is a virtual property that can be overridden any predefined class exception will override the message property to provide the error message specific to the exception.
Message is a read-only property which contains only the get block in it.so predefined exception will be internally defined as following.
Prototype:

Public class :exception
{
Public override string message
{
get{return "";}
}
}

Note:
The above prototype used to, if required you can also define our own exception classes.

Try, Catch and Finally:



These three blocks can be used in3 different combinations.

1.try and catch:
Here any exception that in a program gets handled.

2.try ,catch and finally:
There will be same as above but all the statements in the finally block gets executed at any cost.
3.try and finally:
Here exceptions are not handled when they occur so abnormal termination will not stop. But even if the program is abnormally going to terminated finally block gets executed.

Types of Exceptions:



Exceptions are of two types:

1.System Exceptions(Pre defined)
2.Application Exceptions(User defined)

An Exception which gets raised implicitly on some predefined error conditions is an system exceptions .
Ex:-
Divide by zero, file not found exceptions

An exception which gets raised by the programmer specific to his application on any user defined condition is an application on Exception. These are purely user defined Exceptions.

How can a programmer raise an exception:

If the programmer wants to raise an exception he can follow the below process.

1.Create the object of an exception class.
FormatException ex=new FormatException();
2.now throw the object using throw statement
throw

throw ex;
(or)
throw new FormatException();


If we want to raise our own exception within a program we can follow any of these processors.

1. Create object of application exception class by providing the error message it has to display whenever an exception is raises as a parameter to its constructor.
ApplicationException ();

2. create our own exception class by giving our own name to it for our requirements following the prototype of our class we have same as above.

Public class < Exceptionname>: Exception
{
Public override string message
{
get {return "msg" ;};
}
}


EX:Add a class throwdemo.cs


namespace oopsprogect
{
Class oddnumberException: Exception
{
Public override string message
{
Get
{
return "divisor cannot be an odd number";
}
}
}
Class throwdemo
{
int x, y,z;
Console.WriteLine("enter x value");
x=int.Parse(Console.WriteLine());
Console.WriteLine("enter y value");
y=int.Parse(Console.WriteLine());
if(y%2>0)
{
//throw new oddnumberException();
throw new application Exception("divisor can't be an odd number:");
}
z=x/y;
Console.WriteLine(z);
Console.WriteLine("end of the program");
}
}


Article by naveensanagasetti
I hope you enjoyed to read my article, If you have any queries out of this then please post your comments.

Follow naveensanagasetti or read 139 articles authored by naveensanagasetti

Comments

Author: Phagu Mahato16 Aug 2013 Member Level: Gold   Points : 3

Consider below simple code for the need of Exception Handling
using System;
namespace ExceHand
{
class Example
{
static void main()
double e = Divide(8,5);
Console.WriteLine (e);
}
static double Divide(double x,Double y)
{
double r=x/y;
}
}
}

In the above code Divide() returns the result of division . We passed two number in parameter

Author: naveensanagasetti16 Aug 2013 Member Level: Gold   Points : 5

Hi Phagu Mahato,

Already I did that part i think you missed out to check total post. This is the sample I did for Division.


Static void main()
{
int x,y,z;
try
{
Console.Write("enter x value");
x=int.Parse(Console.WriteLine());
Console.Write("enter y value");
y=int.Parse(Console.WriteLine ());
if(y==1)
return;
z=x/y;
Console.WriteLine (z);
}
Catch(Exception ex)
{
Console.WriteLine (ex.message());
}
finally
{
Console.WriteLine ("Final block");
}
Console.WriteLine ("end of the program");
}

Author: Phagu Mahato21 Aug 2013 Member Level: Gold   Points : 1

Thanks naveensanagasetti . Actually I Post only for sample guideline " How to work Exception Handling "

Author: ketan Italiya26 Aug 2013 Member Level: Gold   Points : 6

hey,

this is also helpful.

Before you start reading this article you need to ensure you satisfy all the pre-requisites. You must:

. be familiar with .NET Framework 2.0 or above
. have C# coding skills
. have knowledge of SQL Server 2005 or above
. be familiar with Visual Studio 2005 or above
. be familiar with creating web application in Visual Studio 2005 or above

Overview

Error Handling has always been crucial for an application in a number of ways. It may affect the execution state of the application, or expose sensitive information to a user. If the error handling is not strong, it may aid the attacker, as the errors returned may assist them in constructing correct attack factors.

An important part of secure application development is to prevent leakage of superfluous information to end user. Error messages (if not proper) may give an attacker great insight into the inner workings of an application.
What are Exceptions

Moving on to the definition, exceptions are basically the unforeseen errors that happen in our programs. Most of the time one can (and should) detect and handle application errors in the code. For example, validate user input data, check for null objects,verify the values returned from methods are what one expect, are all examples of good standard error handling that one should be taking care of all the time.
Handling the Anomalies

Tracing and handling of execution time errors is one of the most crucial tasks ahead of any programmer. But, before discussing the same, let's look at compile time errors, which are errors that occur during compilation of application. They may cause due to bad coding, misspelling of syntaxes, and so on.

On the other hand, runtime errors occur at the time the program executes and can't be corrected. A developer can, however, take preventive measures while coding the program. To do so, he should first identify these two aspects:

Discover the parts of a program that are most likely to emit errors at execution time.
Handle those errors according to the language conventions.

When an exception occurs the program flow for the executing method is interrupted. If the exception is not handled explicitly, the method exits and the exception is escalated to the calling function. This calling function has the opportunity to handle that error. The process continues until the exception is handled by the application or it reaches the Language's runtime system.

An unhandled exception that reaches the Language's runtime system causes the immediate, abnormal termination of the program. This can be a problem as the exception is reported to the end user in form of a message or dialog box containing standard information and technical details that may be misunderstood. During debugging this may be useful but in a production system it is generally considered unacceptable. It can also permit the user to attempt to continue to run a program that, due to errors, has become unstable.

A generic custom error page for most errors is recommended. This approach makes it more difficult for attackers to identify signatures of potentially successful attacks. There are methods which can circumvent systems with leading error handling practices which should be kept in mind: Attacks like SQL injection can be used to address such generic responses.

The other key area relating to error handling is the premise of "fail securely". Errors induced should not leave the application in an insecure state. Resources should be locked down and released, sessions terminated (if required), and calculations or business logic should be halted (depending on the type of error, of course).

"The purpose of reviewing the Error Handling code is to assure that the application fails safely under all possible error conditions, expected and unexpected. No sensitive information is presented to the user when an error occurs."
Exception handling in General

C# provides an elegant way to handle runtime errors with the help of the try, catch, and finally keywords. No matter we write a code for a small application or a business level application, the exceptions could be categorized into three basic levels

Level 1. Exception caused by failure of user data validation.

Level 2. Exceptions caused by anomaly in business logic.

Level 3. Application level Exceptions, caused due to application crash, Incorrect/Unexpected output from database, improper hosting of application, Framework level bugs etc.
Exception Handling and .NET
Centralizing the Exception Handling

Level 3 exceptions commonly need to be centralized at application level, so that when an exception having such behaviour occurs, it is taken care of with immediate effects, In .Net this could be achieved by two methods,

A. Handling the Exception in Global.asax.

B. Handling the exception in web.config.

Since these are the exceptions thrown by Runtime Environment, the exact behaviour of this type of exception is hard to trace.
Right Approach

This content focusses more on technical feasibility and implementation of the same, we see here how the points discussed above are disguised in the form of code and learn how to implement these points practically in our application.
The Building Blocks

In .NET a System.Exception object exists. Mostly used child objects such as ApplicationException and SystemException are used. It's not recommended that one throws or catches a SystemException as that is thrown by CLR automatically.

When an error occurs, the system or the currently executing application reports it by throwing an exception containing information about the error. Once an exception thrown, it is handled by the application or by the default exception handler. This exception object contains methods such as:

StackTrace of Exception
Source of Exception
Message in Exception
InnerException of that object

In .NET we need to look at the error handling strategy from the point of view of global error handling and handling of unexpected errors.

To avoid program to crash, the exceptions must be caught using a try-catch statement.

thanks
ketan



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: