Monday, 25 May 2015

Creating custom exception class

Though Java's exception handling covers the whole gamut of errors and it is recommended most of the time that we should go with standard exceptions rather than creating one, but we might need to create our own exception types to handle situations which are specific to our application.

According to Java Docs, you should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.
  • Do you need an exception type that isn't represented by those in the Java platform?
  • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?

When to go for Custom Exception

Think of creating a custom exception only if there is logic in your code for which you want to throw an exception that will give more readability to the exception thrown otherwise stick to some already existing exception.

As Exp. Let's assume there is a code in which based on age some logic is executed for senior citizens (only if entered age is greater than or equal to 60) otherwise it should throw exception. In that case we can create an InvalidAgeException as it will make it more readable and specific to our application logic.

Also in some applications they go with error codes and throw those error codes with in the exception message, in that case also we can create a custom exception with error code and caller program can handle these error codes through a utility method.

Example of custom Exception

If we take the already mentioned InvalidAgeException then it can be implemented the following way.
Note that, here it is implemented as unchecked exception (inheriting from RunTimeException) though custom exception can be implemented as checked exception too.

class InvalidAgeException extends RuntimeException{
 private int age;
 InvalidAgeException(){
  super();
 }
 InvalidAgeException(int age){
  this.age = age;
 }
 InvalidAgeException(String msg, int age){
  super(msg);
  this.age = age;
 }
 InvalidAgeException(String msg, Throwable cause, int age){
  super(msg, cause);
  this.age = age;
 }
 @Override
 public String toString(){
  return "InvalidAgeException for Age: " + getAge();
 }
 @Override
 public String getMessage(){
  return "InvalidAgeException for Age: " + getAge();
 }
 public int getAge() {
  return age;
 }
 
}


public class CustomExceptionDemo {

 public static void main(String[] args) {
  CustomExceptionDemo ceDemo = new CustomExceptionDemo();
  ceDemo.calculateExtraBenefits(45);
 }
 public void calculateExtraBenefits(int age){
  // If age is less than 60 throw exception
  if(age < 60){
   throw new InvalidAgeException(age);
  }
 }
}

Output

Exception in thread "main" InvalidAgeException for Age: 45
 at org.netjs.examples.impl.CustomExceptionDemo.calculateExtraBenefits(CustomExceptionDemo.java:42)
 at org.netjs.examples.impl.CustomExceptionDemo.main(CustomExceptionDemo.java:38)

Custom Exception as checked Exception or Unchecked Exception

There is one rule of thumb while deciding to make custom exception a checked exception or an unchecked exception.

If user can take some action to recover from the expected error then make the custom exception a checked exception. On the other hand if user cannot do anything useful in case of error then make the custom exception as an unchecked exception (i.e. inheriting from RunTimeException).

Most of the time only function of the custom exceptions is to log an error; in that case it should definitely be an unchecked exception.

Prefer unchecked exceptions for all programming bugs: By programming bug I mean invalid input parameters or incorrect method implementation, there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time.

Remember that RunTime and Checked exceptions are functionally equivalent, whatever handling or recovery checked exceptions can do, runtime exceptions can also do. For checked exceptions it has been made sure (forced) that handling is there by making it a compile time error.
Though in Java 7; some steps had been taken to reduce the boiler plate code by introducing try-with-resources and multi-catch statement.

(For a more detailed discussion on differences betweem Checked exception and Unchecked exception refer Checked exception Vs Unchecked exception)

Points to Note

  • Don't create new custom exception classes if they don't provide any useful information for client code. Use any standard exception instead.
  • If the user can take some action to recover from the exception, make custom exception a checked exception. If the user cannot do anything useful, then make the exception unchecked.
  • Generally custom exceptions are used for logging purpose only so better to make them unchecked exception. Anyway we can always catch an unchecked exception too in a try-catch block. It's just that compiler won't force us to do that.
  • Try to provide the parameter that caused the exception in the exception message. As in the above example age is also appended in the exception message. That makes it easy for the programmer who is looking in to the cause of error.
  • There are four constructors provided by Throwable class try to provide all of them in your custom exception class, at least no-arg, one with string (for message) and one which accepts another Throwable as cause. Last one is important in the case we are wrapping the originally thrown error in some custom exception and rethrowing it. In that case having original exception as cause parameter helps in getting to the root cause of the error.

That's all for this topic Creating custom exception. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. Best practices for exception handling in Java
  2. Exception Propagation
  3. Exception handling and method overriding
  4. Multiple catch blocks
  5. Nested try statements
  6. Lambda expression and exception handling
  7. Java Exception Handling interview questions

You may also like -

try-with-resources in Java 7

Java 7 introduced a new form of try known as try-with-resources for Automatic Resource Management (ARM). Here resource is an object that must be closed after the program is finished with it. Example of resources would be an opened file handle or database connection etc.

Note that any resource declared in a try-with-resource statement, will be closed regardless of whether the try statement completes normally or abruptly.

Apart from try-with-resources Java 7 also introduced Multi catch statement to decrease code verbosity.

General Form of try-with-resources

try-with-resources statement is a try statement that declares one or more resources with in parenthesis.

try(// resources declared here){
    // code that uses resources
} catch (ExceptionObject eObj) {
    // exception handling code
}
//When having try-with-resources,finally block is not required as
//resources are closed automatically as soon as try-catch block is executed.

Example of try-with-resources

First let's see how it was done without try-with-resources. Before the introduction of try-with-resources we had to explicitly close the resources once the try block completes normally or abruptly . Usually, finally block of a try-catch statement was used for it.
That's how it looked like -

public class ResourceMgmtDemo {
 public static void main(String[] args) {
  BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("C:\\test.txt"));
            System.out.println(br.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null){
                 System.out.println("Closing the file");
                 br.close();
                }
                    
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Note how finally block is used here to close the file handle. We had to write one whole block just for closing the resources and there again wrap the code in try-catch block.

try-with-resources helps in reducing such boiler plate code. Let's see the same example using try-with-resources

public class ResourceMgmtDemo {
 public static void main(String[] args) {  
        try(BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt"))) {            
            System.out.println(br.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
}

It can be seen how resource is declared with the try statement itself here. Also notice the reduction in the number of lines of code!

How resources are closed automatically

Any resource that is used with try-with-resource is closed automatically because of the interface java.lang.AutoCloseable. AutoCloseable interface has a close method and any resource used with try-with-resources should implement this interface and provide implementation for the close method.

It should be noted that the close method of AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions.
Like in Java 7 Closeable interface extends AutoCloseable and override the behavior of close method to throw IOException. In the above example BufferedReader resource is used which implements the close method of Closeable interface and throw IOException.

Using Multiple Resources

It is possible to use multiple resources inside a try-with-resources block , all of them will be closed automatically.

public class ResourceMgmtDemo {
 public static void main(String[] args) {  
        try(FileReader fr = new FileReader("C:\\test.txt");
         BufferedReader br = new BufferedReader(fr)) {            
            System.out.println(br.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
}

This example creates two resources inside the parentheses after the try keyword. A FileReader and a BufferedReader. Note that created resources should be separated by a semicolon.Both of these resources will be closed automatically when execution leaves the try block.
The resources will be closed in reverse order of the order in which they are listed inside the try parentheses. First the BufferedReader will be closed, then the FileReader.

Suppressed Exceptions

If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown in try block. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

This behavior is different from what will happen in case of try-catch-finally statement. If exceptions are thrown in both try block and finally block, the method returns the exception thrown in finally block.

Let's clarify the difference, with help of example code

public class ResourceMgmtDemo {
 public static void main(String[] args) {  
  try {
   normalTry();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   tryWithResource();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }
 
    private static void normalTry() throws Exception {
     MyAutoResource myAutoResource = null;
        try {
         myAutoResource = new MyAutoResource();
            System.out.println("MyAutoResource created in try block");            
            throw new Exception("Exception in try block");
        } finally {
            if (myAutoResource != null)
             myAutoResource.close();
        }
 
    }
    
    private static void tryWithResource() throws Exception {
        try (MyAutoResource myAutoResource = new MyAutoResource()) {
            System.out.println("MyAutoResource created in try-with-resources");
            throw new Exception("Exception in try-with-resources block");
        }
    }

}
// Custom implementation of AutoCoseable
class MyAutoResource implements AutoCloseable {
  
    @Override
    public void close() throws Exception {
        System.out.println("Closing MyAutoResource");
        // Here exception is thrown
        throw new Exception("Exception in Closing");
    }
}

Output

MyAutoResource created in try block
Closing MyAutoResource
java.lang.Exception: Exception in Closing
 at org.netjs.examples.impl.MyAutoResource.close(ResourceMgmtDemo.java:51)
 at org.netjs.examples.impl.ResourceMgmtDemo.normalTry(ResourceMgmtDemo.java:31)
 at org.netjs.examples.impl.ResourceMgmtDemo.main(ResourceMgmtDemo.java:10)
MyAutoResource created in try-with-resources
Closing MyAutoResource
java.lang.Exception: Exception in try-with-resources block
 at org.netjs.examples.impl.ResourceMgmtDemo.tryWithResource(ResourceMgmtDemo.java:39)
 at org.netjs.examples.impl.ResourceMgmtDemo.main(ResourceMgmtDemo.java:16)
 Suppressed: java.lang.Exception: Exception in Closing
  at org.netjs.examples.impl.MyAutoResource.close(ResourceMgmtDemo.java:51)
  at org.netjs.examples.impl.ResourceMgmtDemo.tryWithResource(ResourceMgmtDemo.java:40)
  ... 1 more

Note that from the try-with-resources block exception that is thrown from the try block is shown but it also shows the exception thrown from try-with-resources block as Supressed exception.

Also note that here a custom implementation of AutoCloseable interface is used with try-with-resource.

Points to note -

  • try-with-resources help in reducing the boiler plate code by providing automatic resource management.
  • With try-with-resources there is no need of having a finally block just to close the resources.
  • Any resource that is used with try-with-resource is closed automatically because of the interface java.lang.AutoCloseable.
  • Multiple resources can be opened in try-with-resources statement separated by a semicolon.
  • try-with-resources along with another feature introduced in Java 7, multi catch statement helps in reducing the number of lines in the code and increasing readability.

That's all for this topic try-with-resources. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. Exception handling and method overriding
  2. Multiple catch blocks
  3. Nested try statements
  4. Multi catch statement in Java 7
  5. Best practices for exception handling in Java
  6. Lambda expression and exception handling
  7. Java Exception Handling interview questions

You may also like -

Saturday, 23 May 2015

final Vs finally Vs finalize

What is the difference among final, finally and finalize in java is one question asked a lot in Java interviews. This question is asked more to confuse a candidate and of course by asking this question you get to assess the knowledge of the candidate about three things final, finally and finalize!
Apart from having ‘final’ in all of these there is no similarity. Though it can be said that primary job of both finally and finalize is to clean up, so there is some similarity in functionality too between the finally and finalize. So let’s go through final, finally and finalize to see where they differ and how.

final – final keyword is used to restrict in some way. It can be used with variables, methods and classes. When a variable is declared as final, its value can not be changed once it is initialized. Except in case of blank final variable, which must be initialized in the constructor.
If you make a method final in Java, that method can’t be overridden  in a sub class.
If a class is declared as final then it can not be sub classed.

finally – finally is part of exception handling mechanism in Java. finally block is used with try-catch block. Along with a try block we can have both catch and finally blocks or any one of them. So we can have any of these combinations try-catch-finally, try-catch, try-finally. finally block is always executed whether any exception is thrown or not and raised exception is handled in catch block or not. Since finally block always executes thus it is primarily used to close the opened resources like database connection, file handles etc.
From Java 7 onwards try with resources provide another way to automatically manage resources.

finalize() - finalize() method is a protected method of java.lang.Object class. Since it is in Object class thus it is inherited by every class. This method is called by garbage collector thread before removing an object from the memory. This method can be overridden by a class to provide any cleanup operation and gives object final chance to cleanup before getting garbage collected.

protected void finalize() throws Throwable
{
    //resource clean up operations
}

Please note that it is not a good idea to rely on finalize() method for closing resources as there is no guarantee when finalize() method will be called by Garbage collector.

That's all for this topic final Vs finally Vs finalize. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. final in Java
  2. finally block
  3. finalize method in Java
  4. Difference between Checked exception & Unchecked exception
  5. Difference between throw and throws
  6. Java Exception Handling interview questions

You may also like -

Difference between throw and throws

throw and throws in Java are two keywords used for exception handling. These two keywords are, functionality wise, very different though.

  • throw is used to throw an exception.
  • throws is used to declare an exception, in the method signature, that can be thrown from a method.

Difference between throw and throws

  1. We can declare multiple exceptions as a comma separated list with throws statement. We can throw only one exception using throw keyword.

    throws Example

    public void displayFile() throws IOException, , ArithmeticException
    

    throw Example

    throw new NullPointerException();
    throw new FileNotFoundException();
    
  2. Where throw is followed by an object of the Exception class, throws is followed by exception class names themselves.

    throw Example

    catch(FileNotFoundException fExp){   
     // throwing fExp which is an object of FileNotFoundException type
     throw fExp;
    }
    
    // creating object and throwing
    throw new FileNotFoundException();
    

    throws Example

    public void displayFile() throws IOException, ArithmeticException
    

    It can be seen that Exception class name itself is in the declaration.

  3. throws clause in used to declare an exception in the signature of the method where as throw keyword is used to throw an exception explicitly with in the code of the method or from a static block.

    throw from a static block

    static int i;
    static int b;
    static {
     System.out.println("in static block");
     try{
      i = 5;
      b = i * 5;
     }catch(Exception exp){
      System.out.println("Exception while initializing" + exp.getMessage());
      throw exp;
     }
     //System.out.println("Values " + i + " " +  b);
    }
    
    

  4. throws clause is used to declare that the method may throw the declared exceptions and calling method should provide the exception handling code where as throw actually throws the exception and the run time system goes through the method hierarchy to search for a method that can handle the exception.

That's all for this topic Difference between throw and throws. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. throws clause
  2. throw statement
  3. Exception handling and method overriding
  4. Exception Propagation
  5. Nested try statements
  6. Difference between Checked exception & Unchecked exception
  7. Java Exception Handling interview questions

You may also like -

Exception handling and method overriding

There are certain restrictions while overriding a method in case of exception handling in Java. Broadly there are two rules -

  • If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception.
  • If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things.
    1. sub-class can declare the same exception as declared in the super-class method.
    2. subclass can declare the subtype exception of the exception declared in the superclass method. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
    3. subclass method can choose not to declare any exception at all.

If superclass method has not declared any exception

If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception.

Example

Exception&method overriding

It can be noted here that parent class' displayMsg() method deosn't have any throws clause whereas overridden method in the subclass declares IOException in its throws clause which is a checked exception. That's why the compile time error.

If we change the throws clause in subclass method to any unchecked exception then it won't result in compiler error.

public void displayMsg() throws ArrayIndexOutOfBoundsException{
}

If superclass method has declared an exception

  1. If superclass method has declared an exception then sub class can declare the same exception as declared in the superclass method.
    class Parent{
        public void displayMsg() throws IOException{
            System.out.println("In Parent displayMsg()");
        }
    }
    public class ExceptionOverrideDemo extends Parent{
        public void displayMsg() throws IOException{  
            System.out.println("In ExceptionOverrideDemo displayMsg()"); 
        }  
    }  
    
  2. subclass can declare the subtype exception of the exception declared in the superclass method.
    class Parent{
     public void displayMsg() throws IOException{
      System.out.println("In Parent displayMsg()");
     }
    }
    public class ExceptionOverrideDemo extends Parent{
     public void displayMsg() throws FileNotFoundException{  
      System.out.println("In ExceptionOverrideDemo displayMsg()"); 
     }  
    
    }
    

    Here in super class displayMsg() method throws IOException where as in subclass overridden displayMsg() method throws FileNotFoundException. Since FileNotFoundException is the subtype (Child class) of IOException so no problem here.

  3. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
    Exception & method overriding2
    Here parent class method is throwing IOException whereas in the subclass overridden method is throwing Exception, it will result in compiler error as IOException is the child class of Exception class, thus Exception is up in the hierarchy.
  4. Subclass overridden method declares no exception. Subclass overridden method can choose to not throw any exception at all even if super class method throws an exception.
    class Parent{
        public void displayMsg() throws IOException{
            System.out.println("In Parent displayMsg()");
        }
    }
    public class ExceptionOverrideDemo extends Parent{
        public void displayMsg(){  
            System.out.println("In ExceptionOverrideDemo displayMsg()"); 
        }  
    
    }
    

That's all for this topic Exception handling and method overriding. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. Java Exception Handling interview questions
  2. Method overriding in Java
  3. throws clause
  4. throw statement
  5. Creating custom exception class
  6. Multi catch statement in Java 7

You may also like -

Exception Propagation in Java exception handling

When an exceptional condition occurs within a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.
The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.
If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. This process of going through the method stack is known as Exception propagation.

An Example with unchecked Exception

public class ExceptionPropagation {

 public static void main(String[] args) {
  ExceptionPropagation exObj = new ExceptionPropagation();
  exObj.method1();
  System.out.println("After handling exception...");
 }
 
 void method3(){
  System.out.println("In method3");
  // This will result in Arithmetic Exception
  // as an attempt is made to divide by zero
  int result = 7/0;  
 }
 
 // This method will forward the exception
 void method2(){
  System.out.println("In method2");
  method3();
 }
 
 // Exception will be handled here
 void method1(){
  try{
   method2();
  } catch(Exception e){
   System.out.println("Exception caught");
  }
 }
}

Output

In method2
In method3
Exception caught
After handling exception
exception propagation in Java exception handling
Searching the stack for appropriate Exception Handler

In case of checked exception compiler forces us to put try-catch block so exception has to be handled where it is thrown. If we don't want to do that then we have to declare it in throws clause. Then exception will propagate to the calling method and it should be caught there or it should be declared in throws clause of that method signature.

public class ExceptionPropagation {

 public static void main(String[] args) {
  ExceptionPropagation exObj = new ExceptionPropagation();
  exObj.method1();
  System.out.println("After handling exception");
 }
 
 // This method declares the exception in throws clause
 void method3() throws FileNotFoundException{
  System.out.println("In method3");
  // throwing exception
  throw new FileNotFoundException();  
 }
 
 // This method also declares the exception in throws clause
 void method2() throws FileNotFoundException{
  System.out.println("In method2");
  method3();
 }
 
 // Exception will be handled here
 void method1(){
  try{
   method2();
  } catch(FileNotFoundException ex){
   System.out.println("FileNotFoundException caught");
  }
 }
}

That's all for this topic Exception propagation in Java exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. throws clause
  2. Difference between throw and throws
  3. try-with-resources in Java 7
  4. Best practices for exception handling in Java
  5. Java Exception Handling interview questions

You may also like -

Friday, 22 May 2015

Multiple catch blocks in Java exception handling

There might be a case when a code enclosed with in a try block throws more than one exception. To handle these types of situations, two or more catch clauses can be specified where each catch clause catches a different type of exception. When an exception is thrown, each of the catch statement is inspected in order, and the first one whose type matches that of the thrown exception is executed.
After one of the catch statement, with in the catch block, executes, the others are bypassed and execution continues after the try-catch block.

Notice that with Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code.

Example

In this program there is an array with only one element which is zero. From main method, while calling this method a parameter is passed which is used as an index of the array. First time 0 is sent which will mean divide by a[0]. Since the value at that index is 0 thus it will result in divide by 0 and exception will be thrown. Next time 2 is sent but array has only one element so trying to access a[2] will result in ArrayIndexOutOfBoundsException. Both of these exceptions will be caught by separate catch blocks.

public class MultipleCatchDemo {
    private void calculateValue(int i){
        int a[] = {0};
        try{
            int b = 7/a[i];
        }catch(ArithmeticException aExp){
            aExp.printStackTrace();
        }catch(ArrayIndexOutOfBoundsException aiExp){
            aiExp.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MultipleCatchDemo mcDemo = new MultipleCatchDemo();
        mcDemo.calculateValue(0);
        mcDemo.calculateValue(2);
    }
}

Output

java.lang.ArithmeticException: / by zero
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:21)
java.lang.ArrayIndexOutOfBoundsException: 2
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:22)

Restriction with Multiple catch blocks in Java

When multiple catch statements are used, it is important to follow the order where the exception sub type is caught before any of their super type. Which means a catch block that catches an exception subclass must come before the catch clause that catches an exception super class.

This is because a catch statement that uses a super class will catch exceptions of that type plus any of its subclasses. Thus, a catch block which catches an Exception subclass would never be reached if it comes after its super class. Note that in Java, unreachable code is an error so this situation will result in a compiler error.

Example

In the same code as used above if one more catch clause is added, as the first one, which uses Exception as parameter, that will result in compiler error.

multiple catch blocks

That's all for this topic Multiple catch blocks in Java exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. Best practices for exception handling in Java
  2. try-catch block
  3. Nested try statements
  4. Lambda expression and exception handling
  5. throws clause
  6. try-with-resources in Java 7
  7. Creating custom exception class

You may also like -

finally block in Java exception handling

When an exception occurs in the code, the flow of the execution may change or even end abruptly. That may cause problem if some resources were opened in the method.
As exp if a file was opened in a method and it was not closed in the end as some exception occurred then the resources may remain open consuming memory. finally provides that exception-handling mechanism to clean up.

Code with in the finally block will be executed after a try/catch block has completed. The finally block will be executed whether or not an exception is thrown.

If the code with in try block executes without throwing any exception, the finally block is executed immediately after the completion of try block. If an exception is thrown with in the try block, the finally block is executed immediately after executing the catch block which handled the thrown exception.

Example of finally

Even if there is a return statement in try block finally will be executed.

public class FinallyDemo {

 public static void main(String[] args) {
  int i = displayValue();
  System.out.println("Value of i " + i);

 }
 
 static int displayValue(){
  try{
   System.out.println("In try block");
   return 1;
  }finally{
   System.out.println("In finally block");
   return 2;
  }
 }

}

Output

In try block
In finally block
Value of i 2

It can be seen though try block has a return value still finally is executed. Ultimately return value is what finally retruns.

Even if the exception is thrown still return value will be what finally returns. Let's see the same example again, this time an exception will be thrown.

public class FinallyDemo {

 public static void main(String[] args) {
  int i = displayValue();
  System.out.println("Value of i " + i);

 }
 
 static int displayValue(){
  try{
   System.out.println("In try block");
   throw new NullPointerException();
  }catch(NullPointerException nExp){
   System.out.println("Exception caught in catch block of displayValue");
   return 2;
  }finally{
   System.out.println("In finally block");
   //return 3;
  }
 }

}

Output

In try block
Exception caught in catch block of displayValue
In finally block
Value of i 3

Please note that it is not a good idea to return any thing from finally as it will suppress the exception. finally must be used for cleaning up.

Points to note -

  • Every try block must be followed by at least one catch or a finally clause. So we can have any of these combinations try-catch, try-finally or try-catch-finally blocks.
  • When method is about to return from its try-catch block after normal execution flow or because of an uncaught exception, finally block is executed just before the method returns.
  • If there are multiple catch blocks and none of them can handle the exception thrown, even then the finally bock is executed.
  • Though there can be multiple catch blocks associated with a single try statement but there can only be single finally block associated with a try block. In case of nested try blocks there can be associated finally blocks with respective try blocks.
  • Finally block is used to close the allocated resources (like file handles, database connections) before returning from the method.
  • It's not a good idea to return any value from finally as it may cause any exceptions that are not caught in the method to be lost.
  • If the JVM exits (through System.exit() or JVM crash) while the try or catch code is being executed, then the finally block may not execute. In case of multithreading if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

That's all for this topic finally block in Java exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. final in Java
  2. finalize method in Java
  3. final Vs finally Vs finalize
  4. How to create a custom exception class
  5. Exception handling and method overriding
  6. Multiple catch blocks
  7. Nested try statements
  8. Lambda expression and exception handling

You may also like -

Difference between Checked & Unchecked exceptions

Before going into the differences between the checked and the unchecked exceptions let's first see what these two types of exceptions are.

Checked Exception in Java

As we know from the exception hierarchy that Throwable is the parent class of all the Exception types. Immediately below Throwable there is a subclass called Exception. This Exception class has one subclass called RunTimeException.

difference between checked and unchecked exception

If an exception is a subclass of Exception but does not inherit from RuntimeException, it is a checked exception. The restriction with a checked exception is that it needs to be either caught in a method (with in a try/catch block), or the method needs to specify that exception in a throws clause declaration.

Java's checked exceptions

  • IOException
  • FileNotFoundException
  • ParseException
  • ClassNotFoundException
  • CloneNotSupportedException
  • InstantiationException
  • InterruptedException
  • NoSuchMethodException
  • NoSuchFieldException

Unchecked Exception in Java

With in the exception hierarchy if an exception is a subclass of RuntimeException, it is an unchecked exception. An unchecked exception can also be caught by wrapping the code in try-catch block, but it does not have to as it is not verified at compile time. Thus the name 'unchecked'.

Most of the times these exceptions occur due to the programming errors. Unchecked exceptions can be thought of arising due to not having a proper testability condition with in a program. Take 3 examples.

  • NullPointerException - If already tested for null using if condition it won't arise.
  • ArrayIndexOutOfBoundsException - If already tested for length of an array it won't arise.
  • ClassCastException - if already checked using instanceof operator it won't arise.

Java's unchecked exceptions

  • ArrayIndexOutOfBoundsException
  • ClassCastException
  • IllegalArgumentException
  • IllegalStateException
  • NullPointerException
  • NumberFormatException
  • AssertionError
  • ExceptionInInitializerError
  • StackOverflowError
  • NoClassDefFoundError

Difference between checked exception and unchecked exception

Now when we know what are checked and unchecked exceptions, it is easy to differentiate between the two -

  • Checked Exception is a direct subclass of Exception where as unchecked exception is a subclass of RunTimeException.
  • Checked exception should be wrapped in a try-catch block or specified as throws clause where as there is no such requirement for unchecked exception.
  • Failure to provide exception handling mechanism for checked exception result in compiler error whereas no compile time error for unchecked exception.
  • Checked exceptions are designed to reduce the number of exceptions which are not properly handled and where there is a reasonable chance for recovery. UnCheckedExceptions are mostly programming errors.

Usage of checked exception

There is a lot of debate over whether checked exceptions are at all needed or not. General complain is that having checked exceptions result in a lot of boiler plate code. That problem has been recognized and Java7 has a feature called multi-catch to reduce exception handling code.

For checked exceptions Java language Specification says; "This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled".

Checked Exceptions should be used to declare expected errors from which there are chances to recover from. It doesn't make sense telling callers to anticipate exceptions that they cannot recover from.

As exp. If a user attempts to read from a non-existing file, the caller can prompt him for a new filename. On the other hand, if the method fails due to a programming bug (invalid input parameters or incorrect method implementation) there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time.

Why unchecked exception

According to the Java Language Specification "run-time exception classes are exempted because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in exceptions at run time. The information available to a Java compiler, and the level of analysis a compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers."

Proper usage of Unchecked Exception

One of the best practices for the exception handling is to preserve loose coupling. According to that an implementation specific checked exception should not propagate to another layer. As Exp. SQL exception from the DataAccessCode (DAO layer) should not propagate to the service (Business) layer. The general practice in that case is to convert database specific SQLException into an unchecked exception and throw it.

catch(SQLException ex){
    throw new RuntimeException("DB error", ex);

Points to note -

  • Checked exception classes are direct descendant of Exception class.
  • Unchecked exception classes are direct descendant of RunTimeException class, where RunTimeException class is the sub class of Exception class.
  • Checked exception must be handled either using try-catch block or declared using throws, not doing that will result in compile time error.
  • Not handling unchecked exception does not result in compile time error.
  • RunTime and Checked exceptions are functionally equivalent, whatever handling or recovery checked exceptions can do, runtime exceptions can also do. For checked exceptions it has been made sure (forced) that handling is there by making it a compile time error.

That's all for this topic Difference between Checked & Unchecked exceptions. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. finally block
  2. final Vs finally Vs finalize
  3. Exception handling and method overriding
  4. Multi catch statement in Java 7
  5. try-with-resources in Java 7
  6. Nested try statements
  7. Java Exception Handling interview questions

You may also like -

Wednesday, 20 May 2015

Multi-catch statement in Java 7

There has always been criticism of checked exceptions in Java exception handling for being verbose and cluttering the code with try-catch blocks.
In Java 7 two features - Try-with-resources (Automatic resource management) and Multi-catch statement have been added to mitigate that problem to certain extent.
In this post we'll talk about multi-catch statement.

Handling more than one type of exception without Java 7 multi-catch

Before Java 7 multi-catch statement, if two or more exceptions were handled in the same way, we still had to write separate catch blocks for handling them.

catch(IOException exp){
    logger.error(exp);
    throw exp;
}catch(SQLException exp){
    logger.error(exp);
    throw exp;
}

It can be noted here that; though the catch blocks are doing the same thing, it is difficult to create a common catch block to eliminate duplicate code because variable exp has different types in both of the catch block.

Handling more than one type of exception with Java 7 multi-catch statement

With Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Each exception type within the multi-catch statement is separated by Pipe symbol (|).

catch(IOException | SQLException exp){
    logger.error(exp);
    throw exp;
}

Note that If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter exp is final and therefore you cannot assign any values to it within the catch block.

According to JavaDoc - "Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers."

Multi-catch statement & Exception hierarchy

While joining multiple statement using | make sure that you go from subtype exception class to parent exception classes. Doing something like this will result in compiler error.

// This will give compiler error
catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException ex){
  ex.printStackTrace();
}

Here first exception itself is Exception which is up in the hierarchy than the other two exceptions. Thus it will give compile time error.

Also, specifying two or more exceptions of the same hierarchy in the multi-catch statement will result in compile time error.
As exp. - the following catch statement will give compile error because FileNotFoundException is a subtype of the IOException class.

catch (FileNotFoundException | IOException ex) {    
 Logger.error(ex);   
}

That's all for this topic Multi-catch statement. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. try-with-resources in Java 7
  2. Difference between Checked exception & Unchecked exception
  3. Difference between throw and throws
  4. final Vs finally Vs finalize
  5. finally block
  6. Multiple catch blocks
  7. Java Exception Handling interview questions

You may also like -

References : http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html

Tuesday, 19 May 2015

Nested try statements in Java exception handling

A try-catch-finally block can reside inside another try-catch-finally block that is known as nested try statement.

In case a try-catch block can not handle the exception thrown the exception goes up the hierarchy (next try-catch block in the stack) and the next try statement's catch block handlers are inspected for a match. If no catch block, with in the hierarchy, handles the thrown exception then the Java run-time system will handle the exception.

public class NestedTryDemo {
    public static void main(String[] args) {
        try{
            System.out.println("In Outer try block");
            try{
                System.out.println("In Inner try block");
                int a = 7 / 0;
            }catch (IllegalArgumentException e) {
                System.out.println("IllegalArgumentException caught");
            }finally{
                System.out.println("In Inner finally");
            }
        }catch (ArithmeticException e) {
            System.out.println("ArithmeticException caught");
        }finally {
            System.out.println("In Outer finally");
        }
    }
}

Output

In Outer try block
In Inner try block
In Inner finally
ArithmeticException caught
In Outer finally

In this example, one try catch finally sequence has been nested within another try catch finally sequence. The inner try block throws an ArithmeticException which it could not handle, as the inner catch block catches IllegalArgumentException. Hence, this exception moves up the hierarchy and handled in the outer try-catch-finally block.

That's all for this topic Nested try statements in Java exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. final Vs finally Vs finalize
  2. Difference between Checked exception & Unchecked exception
  3. Difference between throw and throws
  4. How to create a custom exception class
  5. try-with-resources in Java 7
  6. Java Exception Handling interview questions

You may also like -

throws keyword in Java exception handling

If in a method we don't want to handle any exception but want to leave it to the calling method to handle any exception that is thrown by the called method, it is done using throws keyword.

Using throws a method can just declare the exception it may throw and callers of the method have to provide exception handling for those exceptions (or they can also declare them using throws).

General form of a method declaration that includes a throws clause

type method-name(parameter-list) throws exception-list
{
// body of method
}

Here, exception-list is a comma-separated list of the exceptions that a method can throw.

Throws is necessary for all checked exceptions only. If a method may throw checked exceptions and does not provide any exception handling for it then those exception must be declared in the throws clause. If they are not, it will result in a compile-time error.

For unchecked exception anyway compiler doesn't force any try-catch block so throws is also optional, not declaring unchecked exception in a throws clause won't result in any compiler error.

Example if Throws is not used with Checked exception

throws keyword

It can be seen that it results in compiler error as the method has no try catch block to handle exception and it is not even declaring the thrown exceptions using throws clause.

Example with throws

To fix it with throws we need to declare the exception displayFile() method can throw using throws clause. Then in main method we need to enclose the method call in try-catch block to handle the error.

public class ThrowsDemo {
    public static void main(String[] args) {
        try{
            displayFile();
        }catch(IOException ioExp){
            ioExp.printStackTrace();
        }
    }
    static void displayFile() throws IOException{
        System.out.println("In displayFile method");  
        throw new IOException();
    }

}

That's all for this topic throws keyword in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. throw statement
  2. Difference between throw and throws
  3. Best practices for exception handling in Java
  4. Multiple catch blocks
  5. Nested try statements
  6. final Vs finally Vs finalize
  7. Java Exception Handling interview questions

You may also like -

try-catch block in Java exception handling

try block

try block is used to enclose the code that might throw an exception. try block must be followed by either catch or finally block.

General form of try block

try {
    code 
}
catch and/or finally blocks
 

catch Block

catch block is used to handle the exception thrown with in a try block. No code can be between the end of the try block and the beginning of the first catch block.

General form of catch block

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

What will happen if try-catch block is not used

Let's first see what will happen if try-catch is not used in a code that throws exception.

public class ExceptionDemo {
    public static void main(String[] args) {
        int a = 0;
        int b = 7 / a;
        System.out.println("After exception");
    }
}

In this program an attempt is made to divide by 0, which will result in an exceptional condition. When run time system detects that, it creates an Exception object and throws it. Since we are not providing any exception handling of our own it will be caught by the default handler, provided by the Java run-time system.

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero
 at org.netjs.examples.impl.ExceptionDemo.main(ExceptionDemo.java:7)

Note that the line "After exception" is not printed, as default handler automatically terminates the program if an exception occurs.

Using try and catch

It is always good to provide an exception handling of your own. As it helps to maintain the flow of the program and prevents the program from terminating automatically. It will definitely be very confusing for the users of a program if program stops running and prints a stack trace whenever an error occurred. Notice how it was automatically terminated in the above program where no exception handling was provided.
Using try-catch prevents that from happening, let's see it with the same example.

public class ExceptionDemo {

 public static void main(String[] args) {
  try{
  int a = 0;
  int b = 7 / a;
  System.out.println("After exception");
  } catch (ArithmeticException aExp) { 
   System.out.println("Division by zero.");
   aExp.printStackTrace();
  }
  System.out.println("After catch statement.");
 }
}

Notice that the call to println( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Once the catch statement has executed, program control continues with the next line in the program . That's why the line "After catch statement" is printed.

In exceptional handling a well-constructed try-catch should catch and resolve the exceptional condition and then continue on as if the error had never happened.

For example let's take list of values and let it throw the same division by zero exception for one of the item in the list, with a proper exception handling it should continue with the next item in the list, rather than terminating the program.

public class ExceptionDemo {

 public static void main(String[] args) {
  int b = 0;
  List <Integer> numList = new ArrayList<Integer>();
  // Putting values in a list
  numList.add(2);
  numList.add(3);
  numList.add(0);// putting zero
  numList.add(6);
  numList.add(8);
  // looping the list and dividing 24 by each 
  // integer retrieved from the list
  for(Integer i: numList){
  try{
   System.out.println("Dividing by " + i);
   // Division by zero will throw exception
   b = 24 / i;
  }catch (ArithmeticException aExp) { 
   System.out.println("Division by zero.");
   // Setting value to zero in case
   // of exception
   b = 0;
   aExp.printStackTrace();
  } 
   System.out.println("Value of b " + b);
  } 
  System.out.println("After for loop");
 }

}

Output

Dividing by 2
Value of b 12
Dividing by 3
Value of b 8
Dividing by 0
Division by zero.
java.lang.ArithmeticException: / by zero
Value of b 0 at org.netjs.examples.impl.ExceptionDemo.main(ExceptionDemo.java:23)

Dividing by 6
Value of b 4
Dividing by 8
Value of b 3
After for loop

It can be seen how in case of division by zero an exception is thrown, which is caught in the catch block and a default value of 0 is given to b in that case. After that for loop goes on with the next element in the list as if nothing happened.

Points to note -

  • There are three exception handler components - the try, catch, and finally blocks to write an exception handler.
  • try block code must be surrounded by curly braces.
  • If there is a catch block, it must immediately follow a try block.
  • finally block can also be used just after the try block without having a catch block.

That's all for this topic try-catch block in Java exception handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!



Related Topics

  1. Best practices for exception handling in Java
  2. Exception Propagation
  3. Exception handling and method overriding
  4. Multiple catch blocks
  5. Nested try statements
  6. final Vs finally Vs finalize
  7. Lambda expression and exception handling
  8. Java Exception Handling interview questions

You may also like -