Tuesday, December 14, 2010

Order of Exceptions

Order of Catch blocks is very importent while implementing the Catch Blocks.For Example if my code is expected to throw DivideByZeroException , If you know the exception type properly you have to write the specifice expected exception then write generic exception. See below example
Ex:
public class Mathematics
{
public int DivisionResult(int x, int y)
{
try
{
return x / y;
}
catch (DivideByZeroException de)
{
return -0;
}
catch (Exception)
{
return -1;
}
}
}


Note1: In the above example if you change the order of Catch you will get compile time error “A previous catch clause already catches all exceptions of this are of a super type (‘System.Exception’)”. This is because of all the exceptions can be caught by the generic catchblock.
Note2: How many catch blocks can i have for a single try block . Answer is no limit.
Note3 : Can i have a try without a catch. Ans: a try should always either have a catch or finally. try will never exist alone ( try cannot be a bachelor ).

No comments:

Post a Comment