Java Exception Interview Questions

What is an exception?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

The exception is said to be thrown whenever an exceptional event occurs in java which signals that something is not correct with the code written and may give unexpected result. An exceptional event is a occurrence of condition which alters the normal program flow. Exceptional handler is the code that does something about the exception.

What is error?

An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.

Which is superclass of Exception?

java.lang.Throwable, the parent class of all exception related classes.

Exceptions are defined in which java package?

All the exceptions are subclasses of java.lang.Exception

How are the exceptions handled in java?

When an exception occurs the execution of the program is transferred to an appropriate exception handler. The try-catch-finally block is used to handle the exception.

The code in which the exception may occur is enclosed in a try block, also called as a guarded region.

The catch clause matches a specific exception to a block of code which handles that exception.
And the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block

What are the advantages of using exception handling?

Exception handling provides the following advantages over “traditional” error management techniques:

  1. Separating Error Handling Code from “Regular” Code.
  2. Propagating Errors Up the Call Stack.
  3. Grouping Error Types and Error Differentiation.

What are the types of Exceptions in Java

There are two types of exceptions in Java, unchecked exceptions and checked exceptions.

Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception.

Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked.

Why Errors are Not Checked?

A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be pointlessly.

Why Runtime Exceptions are Not Checked?

The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking 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 runtime exceptions. The information available to a compiler, and the level of analysis the 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.

Explain the significance of try-catch blocks?

Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. One or more catch clauses match a specific exception to a block of code that handles it.

What is the use of finally block?

The finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. This is right place to close files, release your network sockets, connections, and perform any other cleanup your code requires.

Note: If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. It there was an exception thrown, the finally block executes immediately after the proper catch block completes

What if there is a break or return statement in try block followed by finally block?

If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes.

Can we have the try block without catch block?

Yes, we can have the try block without catch block, but finally block should follow the try block.
Note: It is not valid to use a try clause without either a catch clause or a finally clause.

What is the difference throw and throws?

throws: Used in a method’s signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself.

A method that does not handle an exception it throws has to announce this:

  public void myMethod() throws Exception {

throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

To throw an user-defined exception within a block, we use the throw command:

  throw new Exception("Custom message!");

How to create custom exceptions?

You can create Custom exception by extending the Exception class or one of its subclasses.

class CustomException extends Exception {
  public CustomException() { super(); }
  public CustomException(String s) { super(s); }

What are the different ways to handle exceptions?

There are two ways to handle exceptions:
Wrapping the desired code in a try block followed by a catch block to catch the exceptions.
List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

What is difference between ClassNotFoundException and NoClassDefFoundError?

A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible.

Consider if NoClassDefFoundError occurs which is something like



does not mean that the SomeTestClass class is not in the CLASSPATH. It means that the class SomeTestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that’s not found by the ClassLoader. So to find the culprit, view the source of the class in question (SomeTestClass in this case) and look for code using static blocks or static members.

When to make a custom checked Exception or custom unchecked Exception?

If an application can reasonably be expected to recover from an exception, make it a checked exception. If an application cannot do anything to recover from the exception, make it an unchecked exception.

What is StackOverflowError?

The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your application/code has ran out of the memory. It may occur in case of recursive methods or a large amount of data is fetched from the server and stored in some object. This error is generated by JVM.

Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope?

Any Exception that can be thrown by a method is part of the method’s public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method’s programming interface as its parameters and return value.

Once the control switches to the catch block does it return back to the try block to execute the balance code?

No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).

Where is the clean up code like release of resources is put in try-catch-finally block and why?

The code is put in a finally block because irrespective of try or catch block execution the control will flow to finally block. Typically finally block contains release of connections, closing of result set etc.

Is it valid to have a try block without catch or finally?

NO. This will result in a compilation error. The try block must be followed by a catch or a finally block. It is acceptable to omit the either catch or the finally block but not both.

How do you get the descriptive information about the Exception occurred during the program execution?

All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred. It prints the most recently entered method first and continues down, printing the name of each method as it works its way down the call stack from the top.

Why is not considered as a good practice to write a single catch all handler to catch all the exceptions?

You can write a single catch block to handle all the exceptions thrown during the program.

If you use the Superclass Exception in the catch block then you will not get the valuable information about each of the exception thrown during the execution, though you can find out the class of the exception occurred. Also it will reduce the readability of the code as the programmer will not understand what is the exact reason for putting the try-catch block.

What is exception matching?

Exception matching is the process by which the the jvm finds out the matching catch block for the exception thrown from the list of catch blocks. When an exception is thrown, Java will try to find by looking at the available catch clauses in the top down manner. If it doesn’t find one, it will search for a handler for a supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack. This process is called exception matching.