Top 10 Interview questions on Exception handling in Java

UPDATED: 31 May 2015


Can we write try without catch?
Yes we can write try without catch but we must write finally.
try{
   try code...
}finally{
   ...
}

Can we write just try without catch and finally?
try{
   try code...
}
No, We can't write just try. (Already stated this in answer 1)


What is finally block?
finally block used to close resources used in try.
=> finally block will be executed even if exception occurs try block.
=> finally block will be execute even you write return variable from try block.
=> finally block will not be executed when System.exit(exitcode) executed in try block.
try {
   /* finally will be executed */
   /* int a = 1 /0; */  
   /* return; */ 
 
   /* finally will not be executed */
   System.exit(0);
} catch (Exception e) {
   e.printStackTrace();
}finally{
   System.out.println("Finally executed.");
}

Can we write try within try?
try {
   try code...
   try {
      try code... 
   } catch (Exception e) {
      e.printStackTrace();
   }  
} catch (Exception e) {
   e.printStackTrace();
}
Yes we can write nested try-catch.


What is the difference between throw and throws?
-> throw is used for throwing an exception from program.
throw new NullPointerException();
-> throws is used in method definition. When method is causing an exception and it is not handled by method itself then exception is passed to caller method.
public void readFile(String filepath) throws IOException{
   ...
}

Which is super class of all exception?
Throwable is super class of all exception including Class `Exception`.
public class IOException extends Exception

public class Exception extends Throwable

What is difference between checked and unchecked exception?
This is explained with example. Read more on http://www.javaquery.com/2015/05/difference-between-checked-vs-unchecked.html


Does the sequence of catch matter? or Following code will compile?
try {
   try code...
} catch (Exception e) {
   e.printStackTrace();
} catch (NullPointerException ne){
   ne.printStackTrace();
}
Yes, Sub class must be caught first. NullPointerException is sub class of Exception. Above program will give compile time error Unreachable catch block for NullPointerException. It is already handled by the catch block for Exception.


What is try-with-resources?(Java 7 or above)
This is explained with example. Read more on http://www.javaquery.com/2015/04/what-is-try-with-resources-in-java-7-or.html


Can we catch multiple exception in one catch?(Java 7 or above)
Yes we can.
catch (IOException|SQLException ex) {
   throw ex;
}


0 comments :