Thursday, February 10, 2011

Throwing and Catching Exceptions

Exceptions in C# and Java share a lot of similarities. Both languages support the use of the try block for indicating guarded regions, the catch block for handling thrown exceptions and the finally block for releasing resources before leaving the method. Both languages have an inheritance hierarchy where all exceptions are derived from a single Exception class. Exceptions can be caught and rethrown after some error handling occurs in both languages. Finally, both languages provide a mechanism for wrapping exceptions in one another for cases where a different exception is rethrown from the one that was caught. An example of using the exception wrapping capability is a three tier application where a SQLException is thrown during database access but is caught, examined, then an application specific exception is thrown. In this scenario the application specific exception can be initialized with the original SQLException so handlers of the application specific exception can access the original exception thrown if needed. Below are two equivalent code samples that show the similarities between exceptions in both languages.


NOTE: Although exceptions in both languages support methods for getting a stack trace, only Java exceptions have methods that allow one to alter the stack trace.
C# Code
using System;
using System.IO;

class MyException: Exception{

public MyException(string message): base(message){ }

public MyException(string message, Exception innerException):
base(message, innerException){ }


}

public class ExceptionTest {


static void DoStuff(){
throw new FileNotFoundException();
}


public static void Main(string[] args){

try{

try{

DoStuff();
return; //won't get to execute

}catch(IOException ioe){ /* parent of FileNotFoundException */

throw new MyException("MyException occured", ioe); /* rethrow new exception with inner exception specified */
}

}finally{

Console.WriteLine("***Finally block executes even though MyException not caught***");

}

}//Main(string[])

} // ExceptionTest

Java Code

class MyException extends Exception{

public MyException(String message){ super(message); }

public MyException(String message, Exception innerException){ super(message, innerException); }


}

public class ExceptionTest {


static void doStuff(){
throw new ArithmeticException();
}


public static void main(String[] args) throws Exception{

try{

try{

doStuff();
return; //won't get to execute

}catch(RuntimeException re){ /* parent of ArithmeticException */

throw new MyException("MyException occured", re); /* rethrow new exception with cause specified */
}

}finally{

System.out.println("***Finally block executes even though MyException not caught***");

}

}//main(string[])

} // ExceptionTest

No comments:

Post a Comment