Top 30 Exception Handling Interview Questions and Answers [For Freshers & Experienced]

Exception handling is a concept that is implemented in algorithms to handle possible runtime errors, which may disrupt the normal flow of a program. Some of the errors which can be handled using this concept are:

  • ClassNotFoundException
  • IOException
  • SQLException
  • RemoteException
  • RuntimeException:
    • ArithmeticException 
    • NullPointerException
    • NumberFormatException
    • IndexOutOfBoundsException
      • ArrayIndexOutOfBoundsException
      • StringIndexOutOfBoundsException

The merit of this implementation is to prevent a crash of the program if there is an exception while executing the program. Without Exception Handling, the program will throw an error when it encounters an exception, and the rest of the program will not be executed. However, implementing this concept will give a workaround in which the rest of the program is executed if they are independent with respect to the exception incurred. 

Read: Must Read 30 Selenium Interview Questions & Answers: Ultimate Guide

Exception Handling Interview Questions and Answers

1. What do you mean by an exception?

It is an abnormal condition that is sometimes encountered when a program is executed. It disrupts the normal flow of the program. It is necessary to handle this exception; otherwise,it can cause the program to be terminated abruptly.

2. Explain how exceptions can be handled in Java. What is the exception handling mechanism behind the process?

There are three parts to the exception handling mechanism. These are called:

  • Try block: The section of the code which is first attempted to be executed and monitored for any exception that might occur. 
  • Catch block: If any exception is thrown by the ‘try’ block, it is caught by this code section. 
  • Finally block: Code under this section is always executed irrespective of exceptions caught in ‘try’ block, if any. Even if there is no exception, the code under this block will be executed. 

3. Is it possible to keep other statements in between ‘try’, ‘catch’, and ‘finally’ blocks?

It is not recommended to include any statements between the sections of  ‘try’, ‘catch’, and ‘finally’ blocks, since they form one whole unit of the exception handling mechanism. 

try

{

    //Code which is monitored for exceptions.

}

//You can’t keep statements here

catch(Exception ex)

{

    //Catch the exceptions thrown by try block, if any.

}

//You can’t keep statements here

finally

{

    //This block is always executed irrespective of exceptions.

}

4. Will it be possible to only include a ‘try’ block without the ‘catch’ and ‘finally’ blocks?

This would give a compilation error. It is necessary for the ‘try’ block to be followed with either a ‘catch’ block or a ‘finally’ block, if not both. Either one of ‘catch’ or ‘finally’ blocks is needed so that the flow of exception handling is undisrupted. 

5. Will it be possible to keep the statements after the ‘finally’ block if the control is returning from the finally block itself?

This will result in an unreachable catch block error. This is because the control will be returning from the ‘finally’ block itself. The compiler will fail to execute the code after the line with the exception. That is why the execution will show an unreachable code error. 

Dreaming to Study Abroad? Here is the Right program for you

6. Explain an unreachable catch block error.

In the case of multiple catch blocks, the order in which catch blocks are placed is from the most specific to the most general ones. That is, the sub classes of an exception should come first, and then the super classes will follow. In case that the super classes are kept first, followed by the sub classes after it, the compiler will show an unreachable catch block error.

public class ExceptionHandling

{

    public static void main(String[] args)

    {

        try

        {

            int i = Integer.parseInt(“test”);   

//This statement will throw a NumberFormatException //because the given input is string, while the //specified format is integer. 

        }

        catch(Exception ex)

        {

System.out.println(“This block handles all exception types”);

//All kinds of exceptions can be handled in this //block since it is a super class of exceptions.

        }

        catch(NumberFormatException ex)

        {

            //This will give compile time error

            //This block will become unreachable as the

//exception would be already caught by the above //catch block

        }

    }

}

7. Consider three statements in a ‘try’ block: statement1, statement2, and statement3. It is followed by a ‘catch’ block to catch the exceptions that occurred during the execution of the ‘try’ block. Assume that the exception is thrown at statement2. Do you think the statement3 will be executed?  

Statement3 will not be executed. If an exception is thrown by the ‘try’ block at any point, the remaining code after the exception will not be executed. Instead, the flow control will directly come to the ‘catch’ block. 

8. Differentiate error and exception in Java.

The key difference between error and exception is that while the error is caused by the environment in which the JVM(Java Virtual Machine) is running, exceptions are caused by the program itself. For example, OutOfMemory is an error that occurs when the JVM exhausts its memory.

But, NullPointerException is an exception that is encountered when the program tries to access a null object. Recovering from an error is not possible. Hence, the only solution to an error is to terminate the execution. However, it is possible to workaround exceptions using try and catch blocks or by throwing exceptions back to the caller function.

Must Read: Java Interview Questions & Answers

9. What are the types of exceptions? Explain them.

There are two types of exceptions: 

Checked Exceptions

The type of exceptions that are known and recognized by the compiler. These exceptions can be checked in compile time only. Therefore, they are also called compile time exceptions. These can be handled by either using try and catch blocks or by using a throw clause. If these exceptions are not handled appropriately, they will produce compile time errors. Examples include the subclasses of java.lang.Exception except for the RunTimeException.

Unchecked Exceptions

The type of exceptions that are not recognized by the compiler. They occur at run time only. Hence, they are also called run time exceptions. They are not checked at compile time. Hence, even after a successful compilation, they can cause the program to terminate prematurely if not handled appropriately. Examples include the subclasses of java.lang.RunTimeException and java.lang.Error.

10. What is the hierarchy of exceptions in Java?

The java.lang.Throwable is a super class of all errors and exceptions in Java. This class extends the java.lang.Object class. The argument of catch block should be its type or its sub class type only. The Throwable class includes two sub classes:

  1. java.lang.Error : This is a super class for all error types in Java. Common errors included under this are – 
    1. java.lang.VirtualMachineError: Under this –
      1. StackOverFlowError
      2. OutOfMemoryError
    2. java.lang.AssertionError
    3. java.lang.LinkageError: Under this – 
      1. NoClassDefFoundError
      2. IncompatibleClassChangeError
  2. java.lang.Exception: This is a super class of all exception types in Java. Common exceptions under this are – 
    1. RunTimeException
      1. ArithmeticException
      2. NumberFormatException
      3. NullPointerException
      4. ArrayIndexOutOfBoundsException
      5. ClassCastException
    2. java.lang.InterruptedException
    3. java.lang.IOException
    4. java.lang.SQLException
    5. java.lang.ParseException

11. What are runtime exceptions in Java? Give a few examples. 

The exceptions that occur at run time are called run time exceptions. The compiler cannot recognise these exceptions, like unchecked exceptions. It includes all sub classes of java.lang.RunTimeException and java.lang.Error. Examples include, NumberFormatException, NullPointerException, ClassCastException, ArrayIndexOutOfBoundException, StackOverflowError etc.

12. Define OutOfMemoryError in Java.

It is the sub class of java.lang.Error which is encountered when the JVM runs out of memory.

13. Differentiate between NoClassDefFoundError and ClassNotFoundException in Java.

Both NoClassDefFoundError and ClassNotFoundException occur when a particular class is not found in run time. However, they occur under different scenarios. NoClassDefFoundError is when an error occurs because a particular class was present at compile time but it was missing at run time. ClassNotFoundException occurs when an exception is encountered for an application trying to load a class at run time which is not updated in the classpath.

14. Does the ‘finally’ block get executed if either of ‘try’ or ‘catch’ blocks return the control?

The ‘finally’ block is always executed irrespective of whether try or catch blocks are returning the control or not.

15. Is it possible to throw an exception manually? If yes, explain how.

It is possible to throw an exception manually. It is done using the ‘throw’ keyword. The syntax for throwing an exception manually is

throw InstanceOfThrowableType;

Here is an example of using the ‘throw’ keyword to throw an exception manually.

try

{

    NumberFormatException ex = new NumberFormatException(); //Here we create an object for NumberFormatException explicitly

    throw ex; //throwing NumberFormatException object explicitly using throw keyword

}

catch(NumberFormatException ex)

{

    System.out.println(“In this block, the explicitly thrown NumberFormatException object can be caught.”);

}

Read: Top 35 Spring Interview Questions & Answers: Ultimate Guide

16. What do you mean by rethrowing an exception in Java?

The exceptions which are raised in the ‘try’ block are handled in the ‘catch’ block. If the ‘catch’ block is unable to handle that exception, it is possible that it can rethrow the same exception using the ‘throw’ keyword. This mechanism is called rethrowing an exception. The implementation is as follows: 

try

{

    String s = null;

    System.out.println(s.length()); //This statement throws a NullPointerException

}

catch(NullPointerException ex)

{

    System.out.println(“Here the NullPointerException is caught”);

    throw ex; //Rethrowing the NullPointerException

}

17. Why do you use the ‘throws’ keyword in Java?

If it is possible for a method to throw an exception if it could not be handled, it should specify that exception using the ‘throws’ keyword. It will be helpful to the caller functions of that method in handling that exception. The syntax for using the ‘throws’ keyword is,

return_type method_name(parameter_list) throws exception_list

{

     //code

}

Here, exception_list is the list of exceptions which may be thrown by the method. These exceptions should be separated by commas. An example of the code : 

public class ExceptionHandling

{

    public static void main(String[] args)

    {

        try

        {

            methodWithThrows();

        }

        catch(NullPointerException ex)

        {

            System.out.println("NullPointerException thrown by methodWithThrows() method will be caught here");

        }

    }

 

    static void methodWithThrows() throws NullPointerException

    {

        String s = null;

        System.out.println(s.length()); //This statement throws NullPointerException

    }

}

18. It is often recommended to keep clean up operations like closing the DB resources inside the ‘finally’ block. Why is it necessary? 

The ‘finally’ block is always executed irrespective of the fact if exceptions are raised in the ‘try’ block or if the raised exceptions are caught in the ‘catch’ block or not. Keeping the clean up operations in ‘finally’ block ensures the operation of these operations in any case, and will not be affected by exceptions, which may or may not rise. 

19. How would you differentiate between final, finally and finalize in Java?

First, ‘final’ is a keyword that can be used to make a variable or a method or a class as unchangeable. To put it simply, if a variable is declared as final, once it is initialized, its value can not be altered. If a method is declared as final, it cannot be overridden or modified in the sub class. If a class is declared as final, it cannot be extended into further classes. 

Second, ‘finally’ is a block which is used in exception handling along with the ‘try’ and ‘catch’ blocks. This block is always executed irrespective of a raised exception or if the raised exception is handled. Usually, this block is used to perform clean up operations to close the resources like database connection, I/O resources, etc.

Third, the finalize() method is a protected method. It belongs to java.lang.Object class. Every class created in Java inherits this method. The garbage collector thread calls this method before an object is removed from the memory. Before an object is removed from the memory, this method is used to perform some of the clean-up operations.

protected void finalize() throws Throwable

{

    //Clean up operations

}

20. What are customized exceptions in java?

Exception classes can be thrown in Java as per the requirements of the program flow. These exceptions are called user-defined exceptions. They are also called customized exceptions. These exceptions must extend any one of the classes in the exceptions’ hierarchy. 

21. How would you explain a ClassCastException in Java?

When the JVM is unable to cast an object of one type to another type, this exception is raised. It is a RunTimeException.

22. Differentiate between throw, throws and throwable in Java.

First, the keyword ‘throw’ is used to throw an exception manually in Java. Using this keyword, it is possible to throw an exception from any method or block. However, it is essential that the exception must be of type java.lang.Throwable class or it belongs to one of the sub classes of java.lang.Throwable class. 

Second, the keyword ‘throws’ is used in the method signature in Java. If the method is capable of throwing exceptions, it is indicated by this method. The mentioned exceptions are handled by their respective caller functions. It is done either by using try and catch blocks or by using the throws keyword. 

Third, the super class for all types of errors and exceptions in Java is called Throwable. It is a member of the java.lang package. The JVM or the throw statement raises only instances of this class or its subclasses. The catch block should contain only one argument and it should be of this type or its subclasses. In case customized exceptions are created, they should extend this class too. 

23. Explain the StackOverflowError in Java.

This is an error that is thrown by the JVM when the stack overflows in runtime.

24. Is it possible to override a super class method that throws an unchecked exception with checked exceptions in the sub class?

It is not possible because if a super class method throws an unchecked exception, it will be overridden in the sub class with the same exception or any other unchecked exceptions. But, it can not be overridden with checked exceptions.

25. Define chained exceptions in Java.

In a program, one exception can throw many exceptions by inducing a domino effect. This causes a chain of exceptions. It is beneficial to know the location of the actual cause of the exception. This is possible with the chained exceptions feature in Java. This has been introduced since JDK 1.4. For implementation of chained exceptions in Java, two new constructors and two new methods are included in the Throwable class. These are,

Constructors Of Throwable class:

    1. Throwable(Throwable cause): The cause is the exception that raises the current exception.
    2. Throwable(String msg, Throwable cause): The msg string is the exception message. The exception that raises the current exception is the cause here.

Methods Of Throwable class:

    1. getCause() method : The real cause of a raised exception is returned by this method.
    2. initCause(Throwable cause) method : The cause of the calling exception is set by this method.  

26. Which class is defined as a super class for all types of errors and exceptions in Java?

The super class for all types of errors and exceptions is java.lang.Throwable in Java.

27. What can classify as a correct combination of try, catch and finally blocks?

A combination of try and catch block.

try

{

    //try block

}

catch(Exception ex)

{

    //catch block

}

A combination of try and finally block. 

try

{

    //try block

}

finally

{

    //finally block

}

A combination of all three: try, block, finally blocks. 

try

{

    //try block

}

catch(Exception ex)

{

    //catch block

}

finally

{

    //finally block

}

28. Why do you use printStackTrace() method?

This method is used to print detailed information about the exception that occurred.

29. What are some examples of checked exceptions?

Some examples of checked exceptions include ClassNotFoundException, SQLException, and IOException.

30. What are some examples of unchecked exceptions?

Some examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException and NumberFormatException.

Also Read: Must Read 47 OOPS Interview Questions & Answers For Freshers & Experienced

Wrapping up

If you’re interested to learn more about big data, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Prepare for a Career of the Future

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN FULL STACK SOFTWARE DEVELOPMENT
Enroll Today

Leave a comment

Your email address will not be published.

×