20 Frequently Asked Exception Handling in Java Interview Questions and Answers (Updated 2021)

+8

Any Java interview is incomplete without Java exception handling interview questions.  Your Java programs can cope up with the unforeseen circumstances, called exceptions, quite efficiently through Java Exception handling which is a robust and user-friendly mechanism to handle errors in a Java program. 

In this article, we will be covering the 20 most frequently asked exception handling in Java interview questions and answers for experienced and beginners to help them ace the interview. 

The topics we will be covering are: 

  • Introduction to Exception handling in Java 
  • The Java Exception Hierarchy 
  • Types of Exceptions in Java 
  • Java Exception handling keywords 
  • Catching Exception in Java 


Introduction to Exception handling in Java 

What is Java Exception Handling? 

An exception in Java is an occurrence of an unusual event at runtime, which interrupts the normal functioning of the program. If the program is not guided what to do in the case of an exception, it will terminate abnormally at the point of exception, without further executing the program. To avoid such program failures, there is a mechanism called Exception Handling in Java that prevents programs from failing under unanticipated situations. A few examples of exceptions occurring at run-time are: 

  • A program trying to access a non-existent file 
  • Invalid data entered by a user  
  • A program executing an invalid SQL query.  


Why do you need Java Exception Handling?
 

If an exception occurs and there is no try and catch block to monitor and handle it, the program will terminate without executing the subsequent lines. Exception handling in Java is therefore required to ensure that the application does not end abruptly, execute catch and finally blocks in it, and tells it what to do in case of an exception.   


What is the mechanism for handling exceptions in Java?
  

Exception handling in Java is achieved through try, catch, and finally blocks. 

  • try block: The lines of code that are probable of causing an error are enclosed inside a try block so that they can be monitored for exceptions. The try block must be followed by either catch block or finally block or both, otherwise the program will throw a compilation error.  
  • catch block: If a try block throws an exception, the control directly goes to the catch block defined for that particular exception.  If no exception occurs, the program skips the catch block and executes normally. 

  • finally block: This block is optional, but if present, it always gets executed irrespective of the occurrence of an exception in the try block. The finally block can only be used in conjunction with the try-catch block. 


The Java Exception Hierarchy
 

What is the Java Exception Hierarchy? 

exception handling in java class hierarchy diagram
Exception Handling in Java

When an exception occurs during the execution of an application, the JVM creates an Exception object in memory and interrupts the normal flow of the program. The throwable class creates a stack trace and also contains the relevant error message which can be obtained through getMessage() method. JVM then finds and executes a piece of code known as Exception Handler which processes the object of Exception Class. 


What is the difference between Errors and Exceptions?
 

The key differences between errors and exceptions in Java are: 

Errors  Exceptions 
Errors are generally caused by the application environment. Examples are OutOfMemoryError and StackOverflowError  Exceptions are caused by the code of the application itself. Examples are FileNotException and IndexOutOfBoundsException 
It is usually impossible to recover from an error.  The application can recover from an exception by the use of try-catch blocks. 
Errors are classified as unchecked as they are unknown to the compiler and occur at run-time.  Exceptions can either be “checked” or “unchecked,” i.e. they may or may not be caught during compilation. 


Exception Handling Interview Questions: Types of Exceptions in Java


What are the types of Exceptions in Java?
 

There are two types of exceptions based on how they are handled by JVM: 

  • Checked Exceptions 

Checked Exceptions are known during the compilation process. The compiler checks whether the exception is handled or not and throws an error in case it is not handled programmatically. Examples of such exceptions are SQLException, IOException, InvocationTargetException, and ClassNotFoundException. 

  • Unchecked Exceptions  

Unchecked Exceptions or run-time exceptions occur during program execution. These exceptions are not caught during the compilation process. All the exceptions under Error and RuntimeException classes are unchecked. Few examples of unchecked exceptions are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Based on how the exceptions are defined, here are other exception types  

  • Built-In Exceptions 

The exceptions that already exist in the Java libraries are known as Built-in exceptions. All the checked and unchecked exceptions fall under this category.  

  • User-defined Exceptions 

If a user comes across an exception scenario that is not covered by the built-in libraries, Java provides a provision to create a custom exception. A custom or user-defined exception can be constructed by creating a subclass of the ‘Exception’ class.  


How do you implement user-defined exception handling in Java?
 

Here are the steps to execute user-defined exception handling in Java 

  1. Create your user-defined exception class by inheriting the built-in Exception class.  

  1. Next, create a constructor for your custom exception class. You can do this by either writing a default constructor within the CustomException or, you may create a parameterized constructor with a string argument.[Text Wrapping Break] This parameterized constructor can be used to store the details of the exception.  

  1. The ‘throw’ keyword is used to raise the user-defined exception. We create an object of the user-defined exception class and the throw clause to initiate that object.  

Below is a user-defined exception handling program in Java

// This program throws an exception whenever the balance  

// amount is below Rs 1000  

// Example taken from GeekforGeeks 

class MyException extends Exception   

{  

//store account information  

private static int accno[] = {1001, 1002, 1003, 1004};  

 

private static String name[] =  

{"Customer1", "Customer2", "Customer3", "Customer4", "Customer5"};  

 

private static double bal[] =  

{10000.00, 12000.00, 5600.0, 999.00, 1100.55};  

 

// default constructor  

MyException() { }  

 

// parameterized constructor  

MyException(String str) { super(str); }  

 

// write main()  

public static void main(String[] args)  

{  

try {  

// display the heading for the table  

System.out.println("ACCNO" + "\t" + "CUSTOMER" +  

"\t" + "BALANCE");  

 

// display the actual account information  

for (int i = 0; i < 5 ; i++)  

{  

System.out.println(accno[i] + "\t" + name[i] +  

"\t" + bal[i]);  

 

// display own exception if balance < 1000  

if (bal[i] < 1000)  

{  

MyException me =  

new MyException("Balance is less than 1000");  

throw me;  

}  

}  

} //end of try  

 

catch (MyException e) {  

e.printStackTrace();  

}  

}  

} 

  

Runtime Error 

 MyException: Balance is less than 1000 

    at MyException.main(fileProperty.Java:36) 

Output: 

ACCNO    CUSTOMER    BALANCE 

1001    Customer1    10000.0 

1002    Customer2    12000.0 

1003    Customer3    5600.0 

1004    Customer4    999.0 


What are the
dissimilarities between the two types of Java exceptions? 

Here are the differences between the exception types in Java 

Checked Exceptions  Unchecked Exceptions 
A checked exception occurs and can be caught at compile time.  Unchecked exceptions happen during runtime. 
The compiler checks for checked exceptions.  The compiler does not check for unchecked exceptions. 
It is possible to handle checked exceptions thereby avoiding the exception as well as a compilation error.   Unchecked exceptions can’t be caught or handled during compilation because they get generated by the mistakes in the program. 
They are the sub-class of the Exception class.  They are generally sub-class of the Error class. 
The JVM expects the exception to be handled in the program itself.  Unchecked exceptions are not expected to be handled by the JVM. 

 

Exception Handling Interview Questions: Types of Exception Handling Keywords 


What are the different keywords in Exception handling in Java?
 

Five keywords manage Java exception handling. These are: try, catch, throw, throws, and finally. We have already seen try, catch, and finally. Let us differentiate and understand the throw and throws keyword. 


What is the difference between throws and throw keywords in Java?
 

The throws keyword is used to declare an exception in the signature of a method. This keyword can throw multiple exceptions, checked and unchecked both, separated by commas. 

The method declaration will look like this: 

public static void throwsKeywordExample() throws SocketException, ConnectionException 

The throw keyword on the other hand is used to throw exceptions explicitly inside a method.  Unlike throws, there is only one exception per the ‘throw’ keyword.  

void throwKeywordExample() 

{ 

  throw new ArithmeticException("Invalid value"); 

} 


How to differentiate
 between the finally, final, and finalize keywords? 

final, finally and finalize are three different keywords in Java all with specific usage. But they are often confused due to similarity names. Let us understand each of them: 

final: Final is a keyword that is used to apply limitations on a class, function, or variable. You cannot inherit a final class, you can’t override a final method and you can’t change the value of a variable declared as final. 

finally: finally keyword is used along with the try-catch block. This block consists of statements that need to be executed regardless of whether an exception occurs or not, for example, the closing of a database connection, etc.  

finalize: The finalize() method of the Object class is used for clean up processing right before the object is garbage collected. The garbage collector calls this method when it finds that there are no more references to a particular object. 

 

Exception Handling Interview Questions: Catching Exceptions in Java 

What is try-with-resources statement in Java? 

 A try statement that declares one or more resources is called a try-with-resources statement. Examples of resources are input and output stream, a database connection, etc. All such resources need to be closed at the end of the program execution. This statement ensures that the code closes the resources that were opened by the try keyword. 

Here is an example taken from the oracle Java docs. 

The below example reads the first line of a file via an instance of BufferedReader.  BufferedReader is the resource here that needs to be closed after its usage in the program.  

// Try-with-resources example 

static String readFirstLineFromFile(String path) throws IOException { 

    try (BufferedReader br = 

                   new BufferedReader(new FileReader(path))) { 

        return br.readLine(); 

    } 

} 

The try-with-resources is declared by declaring the resource object in parentheses immediately after the try keyword. As a BufferedReader instance is declared inside the try-with-resource statement, it will be closed even if the try statement terminates abruptly. 


What is
stack trace in Java and why is it important in exception handling? 

A stack trace is a list of frames that contains information about methods that were called during your application’s execution. A stack trace gives the names of the methods and classes that were called throughout the lifecycle of the application until the occurrence of an exception. 

In Java exception handling, stack trace can be used as a powerful debugging tool as it helps in determining the exact point where the exception occurred in the application and the reason why it occurred. 


What is a nested try-catch block?
 

In exception handling, a nested try-catch block is one where we use a try-catch block inside another. 

Here is an example of nested try-catch block: 

/**Example taken from Edureka.com**/ 

class Exception{ 

  public static void main(String args[]){ 

    try{ 

      try{ 

          System.out.println("going to divide"); 

          int b=59/0; 

         }catch(ArithmeticException e){System.out.println(e);} 

      try{ 

          int a[]=new int[5]; 

         a[5]=4; 

         } 

        catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);} 

            System.out.println("other statement); 

        }catch(Exception e) 

         {System.out.println("Exception handled");} 

       System.out.println("casual flow"); 

    } 

} 

The above program will try to execute the inner try statement first. If the inner try statement doesn’t find a matching catch statement, the control will be transferred to the subsequent try block. The program will keep looking for catch statements until it succeeds or until all the nested try statements are executed. If no matching catch statement is found, the JRE will handle the exception. 


What is a multi-catch block in Java?
 

There could be a scenario where a single piece of code can cause multiple exceptions. You can handle this situation by creating several catch clauses, each catching a different exception. When the program throws an exception, it inspects the catch statements in the order in which they appear. The first catch whose type matches the type of exception is executed. Below is an exception handling program in Java to understand the multi-catch block. 

// Multi-catch block 

// Code taken from Edureka.com 

public class SampleMultipleCatchBlock{ 

 public static void main(String args[]){ 

    try{ 

       int a[]=new int[5]; 

       a[5]=30/0; 

      } 

      catch(ArithmeticException e) 

        {System.out.println("task1 is completed");} 

      catch(ArrayIndexOutOfBoundsException e) 

        {System.out.println("task 2 completed");} 

      catch(Exception e) 

        {System.out.println("task 3 completed");} 

      System.out.println("remaining code"); 

  } 

} 


What are chained exceptions in Java?
 

By using chained exceptions, you can associate one exception with another exception, i.e, the second exception is generally the cause for the first exception. 

For instance, consider a method that throws an ArithmeticException because it attempted to divide by zero. However, the real cause for that exception was an I/O error that improperly set the divisor. Though the method ought to throw an ArithmeticException, as it is the error that occurred, the calling code should also know that the actual cause was an I/O error.  


How do you catch Multiple Exceptions in a single block of code?
 

There are three ways by which you can catch multiple exceptions in a single code block: 

  1. By using a catch block that handles all the exception types being thrown by a method: 

try { 

    // ... 

} catch (Exception ex) { 

    // ... 

} 

A thing to remember is that the above code is not a recommended method though. It uses the generic Exception class as it handles all the exceptions. However, it is best to use exception handlers that are precise to the exceptions being thrown. 

  1. The second way is to implement multiple catch blocks: 

try { 

    // ... 

} catch (FileNotFoundException ex) { 

    // ... 

} catch (EOFException ex) { 

    // ... 

} 

We need to keep in mind that if the exceptions share an inheritance relationship, the child type has to come before the parent type otherwise it will result in a compilation error. 

  1. The third is to use a multi-catch block which we have already covered in the previous section. 


What will be the result of the main method throwing an exception?
 

If an exception is thrown by the main() method, the Java Runtime Environment will terminate the application and print the stack trace in-system console along with the exception message. 

Exception Handling Best Practices 

What are the best practices in Java exception handling? 

Below are the top 10 best practices to follow for implementing exception handling in Java 

  1. You ought to use a finally block to clean-up resources. Alternatively, you can use a try-with-resources statement. 
  1. You should throw specific exceptions as far as possible. 
  1. You must not catch the Exception class, instead you should catch specific subclasses. 
  1. The Throwable class is not to be caught. 
  1. Make it a habit to correctly wrap the built-in exceptions in custom exceptions to ensure a readable stack trace. 
  1. Catch the most specific exception first 
  1. No exception should be thrown from the finally block 
  1. Avoid calling printStackTrace() or similar methods within your code. 
  1. Your code should validate the user input to minimize user errors as well as catch an adverse condition fairly early. 
  1. Include descriptive messages while throwing exceptions. 

How to use exception handling with method overriding?  

  • When exception handling is used with method overriding, it causes ambiguity. The compiler gets confused as to which method definition it should follow, the one in the superclass or the subclass. Certain rules can help prevent this ambiguity while using exceptions with inheritance.  
  • If the parent class method does not throw exceptions, the overriding class method should throw only unchecked exceptions. A checked exception will result in a compilation error.  
  • In the case of the parent class method throws checked exceptions, the child class method may throw any unchecked exception as well as any or all of the checked exceptions thrown by the superclass. 
  • The child class can also declare a few checked exceptions that the parent class does not throw, but it needs to ensure that the scope of such checked exceptions in the child class is narrower as compared to the parent class.  
  • When the superclass throws an unchecked exception, the subclass method can throw either none or any number of unrelated unchecked exceptions.  

You can understand exception handling in method overriding through code better. 

Now when you are done with the most popular Java exception handling interview questions, we at Hackertrail are here to connect you to the right opportunities in your domain. 

 

+8

Related Articles