Saturday, July 21, 2007

Exception Handling : Try-Catch

Try-Catch statement consists of a try block followed by one or more catch clauses
Try block contains the guarded code block that may cause the exception
Catch block can be used without arguments, in which case it catches any type of exception
Catch block generally has an object argument derived from System.Exception class, in which case it handles a particular type of exception
It is possible to have multiple catch clauses in one try-catch statement
Order of catch statements is important when multiple catches are present

Code Listing: Try-Catch

using System;
class MyClass
{
public static void Main()
{
MyClass x = new MyClass();

try
{
string s = null;
x.MyFn(s);
}

catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
}

catch (Exception e)
{
Console.WriteLine("{0} Second exception caught.", e);
}

}


public void MyFn(string s)
{
if (s == null)
throw new ArgumentNullException();
}

}

No comments:

Post a Comment