Exceptions
allow an application to transfer control from one part of the code to another.
When an exception is thrown, the current flow of the code is interrupted and
handed back to a parent try-catch block. C# exception handling is done with the
following keywords: try, catch, finally, and throw.
Syntax
try
{
//statements that may raise exceptions
}
catch
{
//Catch
the exception
}
finally
{
//this
block of code will always get executed whether an exception occurs or not as
long as there are no exceptions within this
block itself.
}
|
With Multiple
Catch blocks:
try
{
//
statements causing exception
}
catch(
ExceptionName e1 )
{
//
error handling code
}
catch(
ExceptionName e2 )
{
//
error handling code
}
catch(
ExceptionName eN )
{
//
error handling code
}
finally
{
//
statements to be executed
}
|
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class ExceptionHandlingExampleProgram
{
static void Main(string[] args)
{
object o2 = null;
try
{
int i2 = (int)o2; // Error
}
catch (Exception exceptionObj)
{
// log exception from exceptionObj
}
finally
{
// do cleanup work here
}
}
}
}
|