Exception Interview Questions

What is an exception?
  • An exception is thrown whenever an unusual event occurs in Java say for instance there is an incorrect code written it will give an unexpected result.

  • Whenever an exceptional event occurs, it will create a hindrance to the normal flow of the program.

  • Exceptional handler is that snippet of code which helps in catching and resolving the exception.

Learn more about Exception in our Video Tutorial

How are the exceptions handled in Java?
  • Whenever an exception occurs the process of execution of the program is transferred to an appropriate exception handler.

  • The try-catch-finally block is used to handle the exceptions.

  • 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.

Exceptions are defined in which java package?

All the exceptions are subclasses of java.lang.Exception.

Explain the exception hierarchy in java.

Throwable is a parent class of all exception classes. There are two types of exceptions:

'Checked exceptions' and 'unchecked exceptions' or 'RunTimeExceptions'. Both type of exceptions extends 'exception' class.

Exception Hierarchy in Java

What is Runtime Exception or unchecked exception?

Runtime exception represents the problems that occurs because of a programming problem. Such problems include some of the following :

  1. Arithmetic exceptions : eg. Dividing by zero.

  2. Pointer exceptions : eg. Trying to access an object through a null reference.

  3. Indexing exceptions : eg. Attempting to access an array element through an index that is too large or too small.

Runtime exceptions need not be explicitly caught in try catch block as it can occur anywhere in a program and in a typical one there can be numerous. By adding runtime exceptions in every method declaration a program's clarity will get reduced. Thus, the compiler does not require one to catch or specify runtime exceptions (although one can). The solution is to rectify the programming logic wherever the exception has occurred or provide a check.

What is a checked exception?

Checked exceptions forces the programmer to catch them explicitly in try-catch block. It is a subclass of Exception. Example : IOException.

What is difference between an error and exception?

An error is an irrecoverable condition occurring at runtime say for instance 'OutOfMemory' error. These JVM errors cannot be repaired at runtime. Though error can be caught in catch block still the execution of application will come to a halt and is not recoverable.

On the other hand exceptions are conditions that occur because of bad input or human error.

For e.g. 'FileNotFoundException' will be thrown if the specified file does not exist or a 'NullPointerException' will take place if one tries using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

What is the use of 'throws' keyword?

If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the 'throws' clause at the function declaration.

What is a 'throw' keyword?

'Throw' keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application. The exception thrown should be subclass of 'Throwable'.

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. Hence the class from the child classloader is not visible. Consider if 'NoClassDefFoundError' occurs then it would be something like this :

java.lang.NoClassDefFoundError src/com/TestClass But this does not mean that the 'TestClass' class is not in the CLASSPATH. It means that the class 'TestClass' was found by the 'ClassLoader'. However, when one tries to load the class, it runs into an error while reading the class definition. This typically happens when the class in question has static blocks or members which uses a Class that's not found by the ClassLoader. So, in order to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.

What are the possible combinations to write try, catch and finally block?

The try block must be always followed by the try block. If there are more than one catch blocks they all must follow each other without any other block in between. The finally block must follow the catch block if one is present. If the catch block is absent the finally block must follow the try block.

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

If an application can reasonably be expected to recover from an exception then it can be said as a checked exception. If an application cannot do anything to recover from the exception then it is said to be an unchecked exception.

How to create a custom Exception?

To create one's own exception extend the Exception class or any of its subclasses. Say for instance,

  • class New1Exception extends Exception { } // this will create Checked Exception

  • class NewException extends IOExcpetion { } // this will create Checked exception

  • class NewException extends NullPonterExcpetion { } // this will create UnChecked exception

What is StackOverflowError?

The 'StackOverFlowError' is an error object thrown by the runtime system when it encounters that the application/code has ran out of the memory. It may occur in case of recursive methods or when 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 are.

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 instead it goes to finally block (if present).

Where is the clean up code like release of resources 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.

Learn in Detail about Java Programming

Does the order of the catch blocks matter if the exceptions caught by them are not subtype or supertype of each other?

No. If the exceptions are siblings in the exception class's hierarchy i.e. if one Exception class is not a subtype or supertype of the other, then the order in which their handlers(catch clauses) are placed does not matter.

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

No. It is not possible to have a try block without catch or finally block as it 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 of the catch or the finally block but not both of them.

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 it is not considered a good practice to write a single catch all handler instead of 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 that occurred. This will also reduce the readability of the code as the programmer will not understand what is the exact reason for putting the try-catch block.

Can a catch block throw the exception caught by itself ?

Yes, a catch block can throw the exception caught by itself which is called as rethrowing of the exception by catch block. e.g. the catch block below catches the FileNotFound exception and rethrows it again.

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 as exception matching.

What happens if the handlers for the most specific exceptions is placed above the more general exceptions handler?

Compilation would fail in this case if the catch block for handling the most specific exceptions is not placed above the catch block written to handle the more general exceptions.

What happens if the handlers for the most specific exceptions is placed above the more general exceptions handler?

Compilation would fail in this case if the catch block for handling the most specific exceptions is not placed above the catch block written to handle the more general exceptions.

Is an empty catch block legal?

An empty catch block is considered legal by leaving the catch block without writing any actual code to handle the exception caught. e.g. The code below is legal but not appropriate, as in this case you will not get any information about the exception thrown.