»Dotnet Ads
»Message Boards
Message Boards
Dotnet Books
»Member Details
Register
Login
LogOut
Submit Code
Submit Jobs
Submit Projects
»Competition
Community
Winners
Prizes
Write For Us
Members
»Other Resources
Links
Dotnet Resources
|
Exception Handling in C# Exception Handling in C#
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 you think can have a exception.
}
catch(Exception ex)
{
// Statements for handling the exception
}
finally
{
//final code
}
|
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.
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.
Multiple Catch Blocks
try
{
}
catch(DivideByZeroException dbe)
{
Console.WriteLine(dbe.errormessage);
}
catch(Exception e)
{
Console.WriteLine("Exception" );
}
finally
{
Console.WriteLine("Finally Block");
}
|
Throwing an Exception
try
{
throw new DivideByZeroException("Division");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception");
}
|
|