Sunday, October 20, 2013

Return immediately after exception has been capture.

I was being captured by exception. You know what? I miss out the very important point on Exception Handling in JAVA. Let’s take a look on the code below:
public static void main(String args[]) {
 System.out.println("Before Exception");
 try {
  System.out.println("Before throw");
  System.out.println(args[1]);          // (1)
  System.out.println("After throw");
 catch( Exception e ) {
  System.out.println(e);                // (2)
 finally {
  System.out.println("Cleaning resources");
 System.out.println("After Exception");    // (3)
When there is an exception error on (1), immediately (2) will get invoked. Somehow the code will never stop executing after (2) and will continue its execution until (3). This could lead to a disaster if subsequent implementation is highly depends on the process in try block. Thus to play it safe, return the code immediately if exception is being capture in the catch block. No worry on the finally block because the code will still execute giving me a chance to clean up my resources.

No comments: