Frequently asked interview questions on Exception Handling

1. What are the type of exceptions you have faced in your code?

This is the most common question that will be asked by interviewer, I have personally faced this question 6 times out of 10 interviews and answer to this question can be very tricky, because interviewer will derive more questions based on your answer. Tell the name of exception which you can explain perfectly. Personally, I would name

NullPointerException
ClassNotFoundException
NoClassDefFoundException

2. What is the difference between Exception and error?

Errors are not caused by programmers, its something that developers don’t have any control over. There can be lots of external factors like System ran out of memory while executing a program, or a remote file went missing, etc. Remember, a programmer is not responsible for errors in java programs, They are only responsible for exceptions.

Exceptions is any event which occurs during execution of any program and disrupts the normal flow of execution. There are two types of exception namely, checked exception and unchecked exception, A developer must handle the exception which may arise during execution of a program.

3. How can you handle exceptions in java?

We have two ways to handle exceptions in java either by using try catch block or by using throws keyword.

By using Try-catch block: example

try {
  // Risky block of code that can throw exceptions
} catch (Exception ex) {
  // what to do when exception has occured
}

by using throws keyword: example

public String testMethod() throws NullPointerException{
    // method body
}

It is recommended to use try-catch where ever possible as throws keyword terminates the method abruptly where as try-catch is used in a systematic way. we will see this in more details in questions below.

4. Explain different possibility of try, catch and finally block?

Try, catch and finally blocks in java are the most important component of any program, it helps you to recover from exception that may occur at runtime. There are s=certain rules to follow while using exception blocks-

  • A try block can not exist on its own, It is mandatory to provide a catch block or a finally block after a try block.
  • One Try block can have multiple catch statements, but catching exception should be in sequential way. ie. first catch the child exceptions then catch the parent exceptions.
  • Finally block is an Optional block but it is very helpful in wrapping any program in a graceful way when any exception occurs. Finally block gets executed even if exception has occurred or not.
  • You can define a try block without a catch block, but in such cases, you must use finally block

5. Can you use more than one catch statements in a single catch block?

Yes, It is easy task to do, lets see the example below:

try {
    //code
}
catch(NullPointerException e) {
    //handle exception
}
catch(NumberFormatException e) {
    //handle exception
}
catch(Exception e) {
    //handle exception
}

After Java 1.8 you can reduce above 3 catch blocks into one block as below:

try {
    //code
}
catch(NullPointerException | NumberFormatException | Exception e) {
    //handle exception
}

6. What are checked and unchecked Exceptions?

Checked Exceptions: The exceptions which are checked at the compile time are called checked exceptions. If any code within a method generates a checked exception, it must be handled using a throws keyword or by using a try catch block. ex: FileNotFoundException, IOException.

Unchecked Exception: The exceptions which are not checked at the compile time are called unchecked exceptions. In these cases compiler doesn’t know if the block of code will generate any exception or not. Ex: all the Error and RuntimeExceptions are part of unchecked exception.

7. How do you differentiate between Final, finally and finalize keywords in java?

In Java, there is no any specific relation between these three words but as the words looks similar, Interviewer checks your confidence and confusion level by asking this. Answer them in parts.

Final: Final is a keyword. It is used to restrict access to classes, methods and variables. When final is used before a class, that class can not be instantiated, When used before a method, that method can not be overridden and when used before a variable, that variable value can’t be changed.

Finally: It is a block, and is used to place important code. this block will be executed whether the exception has occurred or not.

Finalize: it is method in java. whenever garbage collector is called in java, this method is used to perform the cleanup task.

8. Explain difference between throw and throws and throwable keywords.

Throw keyword in java is used to throw an exception in java from a method or a block of code. We can throw both checked and unchecked exception using throw keyword. Usually throw keyword is used to throw a customized exception. ex:

throw new ArithmeticException("/ by zero");

but this instance must of the type throwable or subclass of throwable.

Throws in java is also a keyword which is used to define method signature to define that this method may throw mentioned exception and caller to such method is responsible to handle such exceptions either by using try-catch block or by using throws keyword. example:

import java.io.IOException;  
public class UseOfThrowAndThrows { 
public static void main(String[] args) 
throws IOException
{
}

Throwable is the superclass of all the exceptions and errors in java. This class is a member of java.lang package. it has two subclasses- 1. Exception, 2. Error

9. When finally block will not be executed?

There can be two situations where finally block is not getting executed.

  • When JVM exits while executing try or catch block.
  • When thread executing try-catch block is interrupted or killed, in these cases finally block may not get executed even though the application as a whole continues.

10. What are user defined exceptions, explain with example?

The exception which are defined by user are called user Defined exception. Ha ha ha…..

Java throwable class defines its own set of exception, ex- NullPointerException, IOException etc but if you are not satisfied with java provided exception, define your own exception. In this situation you have to take help of throwable class or its subclasses. Example:

class InvalidAgeException extends Exception{  
 InvalidAgeException(String s){  
  super(s);  
 }  
}  

11. Can you rethrow same exception from catch handler?

If a catch block cannot handle any particular exception it has caught, we can rethrow that exception. The rethrow causes the originally thrown object to be rethrown.

As the exception has already been caught in the previous scope , it is rethrown out to the next enclosing try block. Example.

public class RethrowException {
   public static void test1() throws Exception {
      System.out.println("The Exception in test1() method");
      throw new Exception("thrown from test1() method");
   }
   public static void test2() throws Throwable {
      try {
         test1();
      } catch(Exception e) {
         System.out.println("Inside test2() method");
         throw e;
      }
   }
   public static void main(String[] args) throws Throwable {
      try {
         test2();
      } catch(Exception e) {
         System.out.println("Caught in main");
      }
   }
}

Output

The Exception in test1() method
Inside test2() method
Caught in main

12. Explain when ClassNotFoundException and NoClassDefFoundError will be raised?

Both ClassNotFoundException and NoClassDefFoundError occurs at the runtime when a particular class is not found. however, they bot occur in different scenarios.

ClassNotFoundException is a runtime exception which is thrown when any application tries to load a class during runtime using the Class.forName() or loadClass() or findSystemClass() methods ,and the class with that specific name is not found in the classpath. 

NoClassDefFoundError is an error that is thrown at the runtime when a class which was available at the compile time but at the runtime JVM was unable to locate that class or the class have moved to other folder or deleted. 

Leave a Reply