Top 25 Java Error and Exception Interview Questions Answers

1) The difference between checked and Unchecked Exceptions in Java?
For checked exceptions, the compiler ensures that they are either handled using try-catch, try-finally, or try-catch-finally block or thrown away. If a method, which throws a checked exception like IOException, and doesn't handle them or doesn't declare them in the throws class of the method, a compile-time error will occur. On the other hand, the compiler doesn't do similar checks for an unchecked exception, that's why it is known as un-checked. These are also called runtime exceptions because they extend java.lang.RuntimeException.

There is another difference between checked and unchecked exceptions,  checked exceptions are those exception classes, which are a subclass of java.lang.Exception but not of java.lang.RuntimeException, on the other hand, the unchecked exception always extends RuntimeException.

Some of the well-known examples of checked exceptions are IOException, SQLException, ParseException, etc, while java.lang.ArrayIndexOutOfBoundsException, IllegalArgumentException and java.lang.NullPointerException has the most seen examples of unchecked exceptions in Java. See my post, checked vs runtime exception for more differences.


2) What is the difference between throws and throws in Java? (answer)

3) Difference between finally, finalize, and finalizer in Java? (answer)

4) What happens when a Thread gets an uncaught exception? (answer)

5) Does finally run always? In which case finally doesn't run? (answer)
Yes, it always run except when your JVM is shutdown or crashed.

6) What is try-with-resources or automatic resource management? (answer)

7) How to get a current stack trace of a Thread? (answer)

8) Difference between Error and Exception in Java? (answer)

9) Difference between NoClassDefFoundError and ClassNotFoundException in Java? (answer)

10) What is chaining of Exception? (answer)

11) How to create custom Exceptions in Java? (answer)

12) Can we have a try block without a catch? (answer)

13) What are the five keywords used in Exception handling? (answer)

14) Can you catch Errors like java.lang.OutOfMemoryError in Java? (answer)


15) What is the problem with the below code?

import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionInterviewQuestion_01 {

    public static void main(String[] args) {
        try {
            multiple();
        } catch (FileNotFoundException | IOException ex) {
            e.printStackTrace();
        }
    }

    public static void multiple() throws IOException, FileNotFoundException{      
           System.out.println("Inside multiple");
    }

}

Output: 
This program will not compile and give you the error  “The exception FileNotFoundException is already caught by the alternative IOException”, because FileNotFoundException is a subclass of IOException.

There are two ways to solve this problem :

1) Use Simple Catch Block and handle FileNotFoundException before IOException

try {
    multiple();
}catch(FileNotFoundException ex){
    ex.printStackTrace();
}catch (IOException  e) {
    ex.printStackTrace();
}

2) Only handle IOException instead of both FileNotFoundException and IOException.

try {
    multiple();
}catch (IOException  e) {
    ex.printStackTrace();
}



You can further see these core Java Courses to learn more about Exception handling in Java.

Java Error and Exception Interview Questions with Answers




16. What does the following program will print?

import java.io.FileNotFoundException;
import java.io.IOException;
import javax.sql.SQLException;

public class ExceptionInterviewQuestion_01 {

    public static void main(String[] args) {
            try {
                test();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {\
                e.printStackTrace();
            }
    }

    public static void test() throws IOException, SQLException, FileNotFoundException{   
              System.out.println("Inside test() method");
    }

}

Output:
This program will also not compile, because we are handling IOException before FileNotFoundException, which is a superclass. So all FileNotFoundException will be caught by the first catch block itself, leaving the second catch block unreachable. If you compile this program, you will get the following error :
Exception in thread "main" java.lang.RuntimeException: 
Uncompilable source code - exception java.io.FileNotFoundException has already been caught
        at test.Test.main(Test.java:22)

You need to rearrange the catch block to fix this problem. See these free Java online courses to learn more about writing code for Exception in Java.

Top 25 Java Exception Interview Questions with Answers



17. What does the following program will print?

import java.io.IOException;
import javax.xml.bind.JAXBException;

public class TestException2 {

    public static void main(String[] args) {
        try {
            foo();
        } catch (IOException e) {
            e.printStackTrace();
        }catch(JAXBException e){
            e.printStackTrace();
        }catch(NullPointerException e){
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void foo() throws IOException{  

    }

}

18. What does the following program will print?

public class TestException3 {

    public static void main(String[] args) {
        try{
        bar();
        }catch(NullPointerException e){
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
           foo();

    }

    public static void bar(){

    }

    public static void foo() throws NullPointerException{

    }

}

This is a trick question, there is no problem with the code and it will compile successfully. We can always catch an Exception or any unchecked exception even if it’s not in the throws clause of the method.

Similarly, if a method (foo) declares the unchecked exception in the throws clause, it is not mandatory to handle that in the program.


19.  What does the following program will print?
hint: - Channing value of Exception Object in multi-catch block

import java.io.IOException;
import javax.sql.SQLException;
public class ExceptionInterviewQuestion_06 {

    public static void main(String[] args) {
        try {
            foo();
        } catch (IOException | SQLException e) {
            e = new Exception("");
            e.printStackTrace();
        }catch(Exception e){
            e = new Exception("");
            e.printStackTrace();
        }
    }

    public static void foo() throws IOException, SQLException{

    }

}

This Java program won’t compile because the exception object in the multi-catch block is final and we can’t change its value. You will get a compile-time error as “The parameter e of a multi-catch block cannot be assigned”. See these Java development courses to learn more about the multi-catch block in Java.

What is improved catch block of Java 7? How to catch multiple exceptions in one catch block?



20. What does the following program will print?
hint: Exception Handling and Method Overriding

public class Parent {

    public void play() throws IOException{
        throw new IOException("tired, can't play");
    }

}

public class Child extends Parent {

    public void play() throws Exception{
        throw new Exception("Let's play");
    }

}

21.  What does the following program will print?
hint: try block not throwing checked Exception

public static void jump(){
   System.out.println("Dil jumping zapak jampak jampak");
}

public static void main(String args[]) {

   try{
      jump();
   }catch(IOException ioe){
      ioe.printStackTrace();
   }

}

22. What is the improved catch block of Java 7? How to catch multiple exceptions in one catch block? (answer)

23. What are some of the best practices you follow while handling Errors and Exceptions in Java? (answer)

24. What are the pros and cons of catching Throwable or Error? (answer)


That's all about some frequently asked Java Error and Exception interview questions. See, how many questions you can answer from this list. I'll post the answer later but if you know the answer you can always share it in the comments section.


Related Java Interview Questions
For my Java EE friends, here are web development specific questions, which you can use to prepare for JEE part:

  • Top 10 Spring Framework Interview Questions with Answers (see here)
  • 10 Great XML Interview Questions for Java Programmers (read here)
  • 50+ Data Structure and Algorithms Interview Questions (questions)
  • 20 Great Java Design Pattern Questions asked on Interviews (see here)
  • 10 popular Struts Interview Questions for Java developers (list)
  • 20+ String Coding Problems from Interviews (questions)
  • 10 frequently asked Servlet Interview Questions with Answers (see here)
  • Top 10 JSP Questions  from J2EE Interviews (read here)
  • 12 Good RESTful Web Services Questions from Interviews (read here)
  • Top 10 EJB Interview Questions and Answers (see here)
  • Top 10 JMS and MQ Series Interview Questions and Answers (list)
  • 10 Great Hibernate Interview Questions for Java EE developers (see here)
  • 10 Great JDBC Interview Questions for Java Programmers (questions)
  • 15 Java NIO and Networking Interview Questions with Answers (see here)
  • 15 Data Structure and Algorithm Questions from Java Interviews (read here)
  • Top 10 Trick Java Interview Questions and Answers (see here)
  • Top 40 Core Java Phone Interview Questions with answers (list)

Thanks a lot for reading this article, if you like this article then please share with your friends and colleagues. If you have any questions or feedback, please drop a note.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.