Top 50 Exception Handling Interview Questions and Answers in Java

In this post, I will be sharing the top 50 exception handling interview questions and answers in java for freshers (0-1 years) and experienced java developers.

I have divided the post into two sections:

1. Face to Face Round Exception Handling Interview Questions and Answers

2. Written/Coding Round Interview Questions

Face to Face Round Exception Handling Interview Questions and Answers:

Q1. What is an Exception in java?

An Exception is a failure condition that occurs during the execution of a program and disrupts the normal flow of the program. It has to be handled properly, failing which program will be terminated abruptly.

Q2. How the exceptions are handled in java?

Exceptions handling can be done using try, catch and finally blocks.

try : The code or set of statements that may raise exception should be try block.
catch : This block catches the exceptions thrown in the try block.
finally : This block of code is always executed whether an exception has occurred in the try block or not except in one scenario explained in below question.

Q3 Is finally block always get executed in the java program?

This question is very important. finally block is always executed but there is one scenario when finally block does not execute.
By using System.exit(0) in the try or catch block, results in finally block does not execute. The reason is System.exit(0) line terminates the running java virtual machine. Termination leads to no more execution of the program.

This is the only scenario when finally block fails to execute.


public class JavaHungry{
    public static void main(String[] args) 
    {
        try
        {
            System.out.println("Inside try block ");
            /* After executing below line
            jvm terminates the program */
            System.exit(0);            
        }
        catch (Exception e)
        {
            System.out.println("Inside catch block");
        }
        finally
        {
            System.out.println("Inside finally block");
        }
    }
}

Output :
Inside try block

Q4. What are the differences between Error and Exception in java?

Main differences between Error and Exception are :

a. Errors are caused by the JVM environment in which the application is running. Example: OutOfMemoryError while Exceptions are caused by the application itself. Example: NullPointerException.
b. Errors can only occur at runtime while Exceptions can occur at compile time or runtime.

You can find more differences between Error and Exception here.

Q5. What statements can exist in between try, catch and finally blocks?

No, try, catch and finally forms a single unit and no other statements should exist in between try, catch and finally blocks.

Q6. Are we allowed to use only try block without a catch and finally blocks?

Prior to Java 7:
No, it is not allowed. If used it shows compilation error. The try block must be followed by a catch block or finally block.

After Java 7 (Correct Answer):
Yes, it is possible to have a try block without a catch and finally blocks. The introduction of try-with-resources concept makes it possible.
The only constraint is resources which we are passing as a parameter in try block must implement AutoCloseable interface.


import java.util.*;

public class JavaHungry{
    public static void main(String[] args) 
    {
        /* After completion of try block,
        the Scanner object would be auto closed
        as Scanner class implements AutoCloseable 
        interface. */
        try(Scanner sc = new Scanner(System.in))
        {
            System.out.println(" try without catch/finally block ");
        }
    }
}

Output :
try without catch/finally block

Q7. What are Checked and Unchecked exceptions in java?

Exceptions which are known to the compiler are called Checked exceptions. Checked exceptions are checked at compile-time only.

Unchecked exceptions occur only at run time. Unchecked exceptions are also called as run time exceptions. All subclasses of java.lang.RuntimeException and java.lang.Error is of Unchecked type.

Q8. What is the difference between Checked and Unchecked exceptions in java?

This is one of the most popular interview questions for java developers. Make sure this question is in your to-do list before appearing for the interview.
Main differences between Checked and Unchecked exceptions are :

a. Checked exceptions are checked at compile time while Unchecked exceptions are checked at run time.
b. Checked exceptions must be handled by try/catch block or throws keyword while Unchecked exceptions are not necessary to handle.

find a detailed explanation here.

Q9. What is the difference between final, finally and finalize in java?

final keyword:
By declaring a variable as final, the value of final variable cannot be changed.
By declaring a method as final, method cannot be overridden.
By declaring a class as final, class cannot be extended.

finally:
Used after try or try-catch block, will get executed after the try and catch blocks without considering whether an exception is thrown or not.

finalize:
Finalize method is the method that Garbage Collector always calls just before the deletion/destroying the object which is no longer in use in the code.

Q10 What is try-with-resources concept in java? How it differs from an ordinary try statement?

According to Java docs, try-with-resources statement is a try statement that declares one or more resources. It ensures that each resource is closed at the end of the statement.

try-with-resources statement can have catch or finally block similar to ordinary try statement. In a try-with-resources statement, JVM makes sure catch or finally block is run after the resources declared have been closed.

Q11. What is RuntimeException in java. Give example?

The exceptions which occur at runtime are called as RuntimeException. These exceptions are unknown to the compiler. All subclasses of java.lang.RuntimeException are RuntimeExceptions.

For example:
NumberFormatException, NullPointerException, ClassCastException, ArrayIndexOutOfBoundException  etc.

Q12. What is the difference between ClassNotFoundException and NoClassDefFoundError in java?

This question is important because very few Java developers are aware of the difference between ClassNotFoundException and NoClassDefFoundError.

ClassNotFoundException:
An exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath is called ClassNotFoundException.

NoClassDefFoundError:
An exception that occurs when a particular class is present at compile-time but was missing at run time is called NoClassDefFoundError.

find a detailed explanation here.

Q13. Can we throw an exception manually/explicitly?

Yes, using throw keyword we can throw an exception manually.

Syntax:

throw InstanceOfThrowableType;

For example:

public class JavaHungry{
    public static void main(String[] args) 
    {
        try
        {
            // Creating an object of ArithmeticException
            ArithmeticException ae = new ArithmeticException();
            //Manually throwing ArithmeticException
            throw ae;
        }
        catch (ArithmeticException e)
        {
            System.out.println("Caught the manually thrown Exception");
        }
    }
}

Output:
Caught the manually thrown Exception


Q14. Does catch block rethrow an exception in java?

Yes, catch block can rethrow an exception using throw keyword. It is called re-throwing an exception.

For example :

public class JavaHungry{
    public static void main(String[] args) 
    {
        try
        {
            // Creating an object of ArithmeticException
            ArithmeticException ae = new ArithmeticException();
            //Manually throwing ArithmeticException
            throw ae;
        }
        catch (ArithmeticException e)
        {
            System.out.println("Rethrowing the caught exception below "); 
            //Rethrowing ArithmeticException 
            throw e;
        }
    }
}

Output :
Rethrowing the caught exception below

Exception in thread "main" java.lang.ArithmeticException
    at JavaHungry.main(JavaHungry.java:7)

Q15. What is the use of throws keyword in java?

throws keyword is used to declare an exception. You can find a detailed explanation here.

Q16. Why it is always recommended that clean up activities like closing the DB connections and I/O resources to keep inside a finally block?

finally block will always be executed except one scenario as discussed above in Q3. By ensuring the cleanup operations in finally block, you will assure that those operations will be always executed irrespective of whether an exception has occurred or not.

Q17. What is OutOfMemoryError in Exception Handling?

OutOfMemoryError is the subclass of java.lang.Error. It occurs when JVM runs out of memory.

Q18. What is ClassCastException in Exception Handling?

RunTimeException which occurs when JVM not able to cast an object of one type to another type is called ClassCastException.

Q19. What is the difference between throws and throw in java?

This is one of the most frequently asked interview questions for java developers.
Main differences between throws and throw are :

a. throws keyword is used when writing methods, to declare that the method in question throws the specified (checked) exception.
throw is used when an instruction is to explicitly throw the exception.
b.  throws is used with a method signature while the throw is used inside a method.

You can find a detailed explanation of the difference between throw and throws in java here.

Q20. What is StackOverflowError in Exception Handling?

StackOverflowError is thrown by the JVM when stack overflows in a program.

Q21. Which class is the root class for all types of errors and exceptions in Exception Hierarchy?

java.lang.Throwable is the superclass for all types of errors and exceptions in java.

Q22. When do we use printStackTrace() method in java?

printStackTrace() function is used to print the detailed information about the exception thrown by the try/catch block.

Q23. Give some examples of Checked exceptions?

SQLException, ClassNotFoundException, IOException

Q24. Give some examples of Unchecked exceptions?

ArrayIndexOutOfBoundsException, NullPointerException, NumberFormatException

Q25. List the Methods in the Throwable class?

Below are the important methods of Throwable class:

•    getMessage()
•    Throwable getCause()
•    toString()
•    printStackTrace()
•    StackTraceElement [] getStackTrace()

Q26. What is a SQLException in Exception Handling?

An exception that provides information related to database access error or other errors is called SQL Exception.

Q27. What is NumberFormatException in java?

NumberFormatException is thrown when you try to convert a String into a number.

Q28. What is ArrayIndexOutOfBoundsException in java?

ArrayIndexOutOfBoundsException arises while trying to access an index of the array that does not exist or out of the bound of this array.

Q29. What will happen if an exception is thrown by the main method?

When an exception is thrown by the main method then JVM terminates the program. As a result, you will find the exception message and stack trace in the system console.

Q30. Is it legal to have an empty catch block?

Yes, we can have an empty catch block in java but it is not the best practice. If an exception is caught by the empty catch block, then we do not have any information about the exception occurred. You should provide at least the logging statement to log the exception details.

Q31. What are the keywords in Java for Exception Handling?

throw, throws, try, catch and finally

Q32. List some important methods of Java Exception class?

a. printStackTrace()
b. toString()
c. getMessage()

Q33. What are the advantages of using Exceptions in your programs?

According to Java doc,

a. Separating "regular" code from error handling code.
b. The ability to propagate errors reporting up the call stack of methods.
c. Differentiating and grouping error types.   

Written/Coding round Interview Questions:

Please go through the below link before attempting questions 46-50.

Q34-45  Programs on Exception Handling in Java with Answers.

Q46. What is unreachable catch block error?
 
When there is more than one catch block, then, the order of catch blocks must be from most specific to most general ones. In other words, subclasses of Exception must come first and superclasses later. If you try to keep superclasses first and subclasses later, the compiler will stop you and show unreachable catch block error.

Q47. Can we provide the statements after finally block if the control is returning from the finally block itself?

No, because control is returning from the finally block itself so it shows unreachable code error.

Q48. Does finally block get executed if either try or catch blocks are returning the control?

Yes, finally block will be always executed no matter whether try or catch blocks are returning the control or not. There is one scenario where finally block does not execute, for more information check out Q3.

Q49.  Suppose there is a catch block corresponding to a try block with three statements – statement1, statement2, and statement3. Assume that exception is thrown in statement2. Does statement3 get executed?

Statement3 will not get executed because once a try block throws an exception, remaining statements will not be executed.

Q50. What will happen if we override a superclass method which is throwing an unchecked exception with a checked exception in the subclass?

If the overridden method throwing an unchecked exception, then the subclass overriding method must have the same exception or any other unchecked exceptions. If you are trying to throw checked exception with subclass overriding method then it will give a compilation error.

Rule of thumb : An overriding method (subclass method) can not throw a broader exception than an overridden method (superclass method).

That's all for today, please mention in comments if you have any questions related to exception handling in java interview questions and answers for freshers and experienced.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry