Java Exception Handling Interview Questions and Answers

Java exception is managed via five keywords: try, catch, throw, throws, and  finally. An exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.

 Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method.

TechShitanshu has prepared a list of the top java Exception Handling interview questions and answers that are frequently asked in the interview. It is going to help you to crack the java interview questions to get your dream job.

java exception handling interview questions

java Exception Handling interview questions and answers

1. What is meant by an exception?

An exception is an abnormal event that disrupts the flow of normal program execution that unless handled could lead to the termination of that program. In real-world scenarios, a program could run into an exception if it tries to access a corrupted/non-existent file or if a network error happens or if the JVM runs out of memory, or if the code is trying to access an index of an array which does not exist and so on.

2. What are Exception Types?

All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses that partition exception handling into two distinct branches. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called RuntimeException.

Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing. The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error. This chapter will not be dealing with exceptions of type Error, because these are typically created in response to catastrophic failures that cannot usually be handled by your program. 

3. What is meant by Uncaught Exceptions?

When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of Exc0 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system.

Any exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program. Here is the exception generated when this example is executed:

 java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) Notice how the class name, Exc0; the method name, main; the filename, Exc0.java; and the line number, 4, are all included in the simple stack trace. Also, notice that the type of exception thrown is a subclass of Exception called ArithmeticException, which more specifically describes what type of error happened. As discussed later in this chapter, Java supplies several built-in exception types that match the various sorts of run-time errors that can be generated

4. How to display a Description of an Exception?

Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of the exception. You can display this description in a println( ) statement by simply passing the exception as an argument. For example, the catch block in the preceding program can be rewritten like this:

 catch (ArithmeticException e) { System.out.println(“Exception: ” + e); a = 0; // set a to zero and continue }

When this version is substituted in the program, and the program is run, each divide-by[1]zero error displays the following message: Exception: java.lang.ArithmeticException: / by zero While it is of no particular value in this context, the ability to display a description of an exception is valuable in other circumstances— particularly when you are experimenting with exceptions or when you are debugging.

5. Is finally block always get executed in the java program?

Finally block is always executed but there is one scenario when finally block does not execute in exception.
By using System.exit(0) in the try or catch block, results in finally block does not execute. The reason is System.exit(0) line terminates the running java virtual machine. Termination leads to no more execution of the program.

6. Is it 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. 

7. What is exception propagation in Java?

To answer this one should know that Exception propagation is a process where the compiler makes sure that the exception is handled if it is not handled where it occurs. If an exception is not caught where it occurred, then the exception goes down the call stack of the preceding method and if it is still not caught there, the exception propagates further down to the previous method. 

If the exception is not handled anywhere in between, the process continues until the exception reaches the bottom of the call stack. If the exception is still not handled in the last method, i.e, the main method, then the program gets terminated. Consider an example –

We have a Java program that has a main() method that calls method1() and this method, in turn, calls another method2(). If an exception occurs in method2() and is not handled, then it is propagated to method1(). If method1() has an exception handling mechanism, then the propagation of exception stops and the exception gets handled

8. What is the difference between exception and error in Java?

Errors typically happen while an application is running. For instance, Out of Memory Error occurs in case the JVM runs out of memory. On the other hand, exceptions are mainly caused by the application. For instance, Null Pointer Exception happens when an app tries to get through a null object.

9. Can we keep other statements in between try, catch and finally blocks?

No. We shouldn’t write any other statements in between try, catch and finally blocks.

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

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

  1. Create user-defined exception class by inheriting the built-in Exception class.
  2. 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.
  3. 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.

11. What are the different keywords in Exception handling in Java?

Five keywords for exception handling are: try, catch, throw, throws, and finally.  

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

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. 

13. Why do we need exception handling in Java?

The program will terminate, if there is no try and catch block while an exception occurs. Exception handling ensures the smooth running of a program without program termination.

14. Can we just use try instead of finally and catch blocks?

No, doing so will show a compilation error. Catch or finally block must always accompany try block. We can remove either finally block or catch block, but never both.

Make sure to prepare for the above-mentioned interview questions on exception handling in Java before appearing for your upcoming interview. You can also look at some of the Top Java Exception Handling Interview Questions and Answers

15. What are the important methods defined in Java’s Exception Class?

The throwable class is the base class of Exception. Exception and its subclasses do not provide specific methods. All the methods that could be used by Exception are defined in the Throwable class. Some of the most important methods are as follows:

  1. String getMessage(): This method returns the Throwable message of type String. The message could be given at the time of creating an exception by using the constructor.
  2. String getLocalizedMessage(): This method can be overridden by the Exception and its subclasses to give locale-specific messages to the calling program. The implementation of this method in the Throwable class by default uses the getMessage() that returns the exception message. Hence, to use this method, it should be overridden to avoid this default behaviour.
  3. synchronized Throwable getCause(): This returns the exception cause if it is known. If the cause is not known, it returns null. The cause is returned if it was provided via the constructors requiring Throwable or if it was set after the creation of exception by using the initCause(Throwable) method. Exception and its subclasses may override this method to return a cause set by different means.
  4. String toString(): This returns the Throwable information in String format consisting of the Throwable class name and localized message.
  5. void printStackTrace(): As the name indicates, this prints the stack trace data to the standard error stream. By default, it prints on the console. But, there are overloaded versions of this method where we can pass either PrintWriter or PrintStream as an argument to write stack trace data to a specific file or stream.

16. There are three statements in a try block – state1, state2 and state3. After that there is a catch block to catch the exceptions occurred in the try block. Assume that exception has occurred in state2. Does state3 get executed or not?

No, state3 is not executed, one of the java exception interview questions. Once a try block throws an exception, remaining statements will not be executed. Control comes directly to catch block.

17. Explain Java Exception Hierarchy?

Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exceptions. 

Errors are exceptional scenarios that are out of the scope of application and it’s not possible to anticipate and recover from them, for example, hardware failure, JVM crash, or out-of-memory error. 

Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example, FileNotFoundException. We should catch this exception and provide a useful message to the user and log it properly for debugging purposes. Exception is the parent class of all Checked Exceptions. 

Runtime Exceptions are caused by bad programming, for example, trying to retrieve an element from the Array. We should check the length of the array first before trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions.

Java Exception Handling Interview Questions

18. What are runtime exceptions in Java?

Runtime exceptions are those exceptions that occur at the run time of the program execution. These exceptions are not noticed by the compiler at the compile time and hence the program successfully gets compiled. Therefore, they are also called unchecked exceptions. All subclasses of the java.lang.RunTimeException class and java.lang.Error class belongs to runtime exceptions. Examples of runtime exceptions include NullPointerException, NumberFormatException, ArrayIndexOutOfBoundException, StackOverflowError, ClassCastException, ArithmeticException, ConcurrentModificationException, etc.

19. what are Java’s Built-in Exceptions?

Inside the standard package java.lang, Java defines several exception handling classes. A few have been used by the preceding examples. The most general of these exceptions are subclasses of the standard type RuntimeException. As previously explained, these exceptions need not be included in any method’s throws list.

 In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. The unchecked exceptions defined in java.lang are listed. 

Table lists those exceptions defined by java.lang that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions. In addition to the exceptions in java.lang, Java defines several more that relate to its other standard packages.

 Exception                                                                           Meaning
ArithmeticException                                        Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException               Array index is out-of-bounds.

ArrayStoreException                                        Assignment to an array element of an incompatible type.
ClassCastException                                         Invalid cast.
EnumConstantNotPresentException            An attempt is made to use an undefined enumeration value.

IllegalArgumentException                               Illegal argument used to invoke a method.

IllegalMonitorStateException                         Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException                                       Environment or application is in incorrect state.

IllegalThreadStateException                           Requested operation not compatible with current thread state.
IndexOutOfBoundsException                          Some type of index is out-of-bounds.
NegativeArraySizeException                           Array created with a negative size.

NullPointerException                                        Invalid use of a null reference.
NumberFormatException                                 Invalid conversion of a string to a numeric format.

SecurityException                                              Attempt to violate security.
StringIndexOutOfBounds                                  Attempt to index outside the bounds of a string.
TypeNotPresentException                                Type not found.
UnsupportedOperationException                    An unsupported operation was encountered.

20. What is Exception Chaining?

Exception Chaining happens when one exception is thrown due to another exception. This helps developers to identify under what situation an Exception was thrown that in turn caused another Exception in the program. For example, we have a method that reads two numbers and then divides them. 

The method throws ArithmeticException when we divide a number by zero. While retrieving the denominator number from the array, there might have been an IOException that prompted to return of the number as 0 that resulted in ArithmeticException. The original root cause in this scenario was the IOException. The method caller would not know this case and they assume the exception was due to dividing a number by 0. Chained Exceptions are very useful in such cases. This was introduced in JDK 1.4

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top