Exception Handling Interview Questions in Java

Exception Handling Interview Questions in Java | In this post, we will see different exception handling interview questions in Java with answers. We will also discuss what are the most frequently asked questions on exception handling in Java?

The 3 most frequently asked questions on exception handling in Java are:-
1) What are the differences between the Exception and the Error?
2) What are the differences between final, finally & finalize()?
3) Difference between checked vs unchecked exceptions?

We will discuss these questions along with many other exception handling interview questions in Java. Let us start with the basic Java exception handling interview questions.

Q1) What is an exception?*

  1. In Java, exception is an object that is an instance of one of the subclasses of java.lang.Throwable.
  2. An exception is an event, which occurs during the execution of a program that disturbs the normal execution flow of the program’s instructions.
  3. It is a signal that indicates some sort of abnormal condition (such as an error) has occurred in a code sequence at run time. 

Example of exceptions:- FileNotFoundException, ArrayIndexOutOfBoundException, ClassCastException, NullPointerException, and e.t.c.

Q2) What is exception handling?*

Exception handling doesn’t mean repairing an exception. We have to provide an alternative way to continue the rest of the program normally, this concept is called exception handling. 

For example:- Our program requirement is to read data from a file located at someplace, but at runtime, if that file is not available then our program should not be terminated abnormally. We have to provide some local files to continue the rest of the program normally. This way of defining alternatives is nothing but exception handling.

Q3) What is the purpose of Exception Handling?
The main objective of exception handling is:- graceful termination of the program.

Q4) Which class acts as a root for all Java exceptions Hierarchy?*
Throwable.

Q5) Throwable is a class or interface?
It is a class, not an interface.

Q6) Throwable class contains how many child classes?
Throwable class contains two child classes:- Exception and Error.

Q7) What is Error?

Most of the time errors are not caused by our programs, these are caused due to the lack of system resources. Errors are not recoverable. For example:- OutOfMemoryError, StackOverflowError.

If OutOfMemoryError occurs, being a programmer we can’t do anything & the program will be terminated abnormally. System admin or server admin is responsible for increasing heap memory.

Q8) What is the difference between Error and Exception?***

Error type exceptions are thrown due to problems occurring inside JVM logic due to the lack of system resources. Example of Error:- OutOfMemoryError, StackOverflowError, VirtualMachineError and e.t.c. Errors are not recoverable. We can’t catch/handle Error type exceptions. Once an Error type exception is thrown then JVM is terminated.

Exception type exceptions are thrown due to the problem occurring in Java program logic execution like integer number divided by zero. Example:- ArithmeticException, NullPointerException, and e.t.c. We can catch/handle Exception type exceptions either through catch block or throws keyword.

Q9) What is the difference between RuntimeException & Exception?

RuntimeException subclasses represent logical mistakes that occurred due to operator execution failure and optional handling exceptions. Exception class represents logical mistakes that occurred due to condition failure of wrong input given by the user.

Q10) What will happen when an exception is raised in the program?

When an exception is raised in a program, the program execution is terminated abnormally. It means statements placed after exception-causing statements are not executed but the statements placed before that exception-causing statement are executed by JVM.

Q11) What will JVM do when an exception (logical mistake) occurs in the program?

JVM creates an exception class object that is associated with that logical mistake and terminates the current method execution by throwing this exception object by using the “throw” keyword.

Q12) How can we handle exceptions in Java?
We can handle exceptions in Java either by using the throws keyword or by using the try-catch block.

Q13) Example of some predefined exception classes?

  1. NullPointerException
  2. ClassCastException
  3. IOException
  4. FileNotFoundException
  5. ClassNotFoundException
  6. NegativeArraySizeException
  7. ArrayIndexOutOfBoundException
  8. StringIndexOutOfBoundException
  9. IllegalArgumentException
  10. NumberFormatException
  11. IllegalThreadStateException
  12. AssertionError
  13. OutOfMemoryError
  14. StackOverflowError
  15. NoClassDefFoundError
  16. ExceptionInInitializerError

try/catch/finally in Exception Handling

Q14) How many keywords are given to work with exceptions?
There are 5 keywords given to work with exceptions, and they are:- try, catch, finally, throw, throws.

Q15) What are the keywords used for handling an exception?
The keywords used for handling an exception are:- “catch”, and “throws”.

Q16) Explain when we will use try/catch/finally & throw/throws keywords?

  1. try:- To place code which can cause an exception.
  2. catch:- To place exception handling code.
  3. finally:- To maintain cleanup code.
  4. throw:- To handover our created exception object to the JVM manually.
  5. throws:- To delegate responsibility of exception handling to the caller method.

Q17) Can finally catch an exception?
No, finally block is used to maintain cleanup code, but not to catch an exception.

Q18) What is the parameter we must use to catch all exceptions using a single catch block?

We can catch all exceptions with a single catch block with the parameter “java.lang.Exception”. We should use this catch block only for stopping abnormal terminations irrespective of the exception thrown from its corresponding try statement. See more:- Catch all Exceptions in Java.

Q19) When should we define multiple catch blocks to a single try block?
We should define multiple catch blocks to a single try block in the following situations:-

  • To print message specific to an exception or,
  • to execute some logic specific to an exception.

Q20) Can we place multiple catch blocks in any order?
No, we must follow the below rules in placing multiple catch blocks:-

  • Catch blocks should not be duplicated.
  • Super class parameter catch blocks should not be placed before child class parameter catch blocks.

Q21) Can an exception be raised in a catch block, if so who will catch that exception?

An exception also can be raised in a catch block. To catch all exceptions we must write try-catch inside the catch block else JVM catches that exception and terminates the program abnormally.

Q22) What is the use of finally block?

As per coding standards in the finally block we should write resource releasing logic (or) clean up code.  Resource releasing logic means unreferencing objects that are created in try blocks.

Q23) When “finally” block is not executed?*

Generally, finally block always executes after try-catch block but there are some situations when finally block don’t get a chance to execute:-

  • System.exit() is called. If we call System.exit() then the program exits immediately without  finally being called.
  • A JVM Crash e.g. Segmentation Fault, will also prevent finally being called. i.e. the JVM stops immediately at this point and produces a crash report.
  • An infinite loop would also prevent a finally being called.

Q24) What are the differences between final, finally, and finalize?***

“final”:- The “final” keyword is a modifier applicable for classes, methods, and variables. If a class is declared as final then we can’t extend that class it means we can’t create a child class for that class. Inheritance is not possible for the final class. If a method is final then we can’t override that method in the child class. If a variable is declared as final then we can’t perform re-assignment for that variable.

“finally”:- The “finally” is a block always associated with try-catch to maintain cleanup code. It will be executed always irrespective of whether an exception is raised or not raised or whether handled or not handled.

try {
   // risky code
} catch(Exception e) {
   // handling code
} finally {
   // cleanup code
}

finalize():- The finalize() is a method always invoked by the garbage collector just before destroying an object to perform cleanup activities. Once the finalize() method completes, immediately the garbage collector destroys that object.

The finally block is responsible to perform cleanup activity related to the try block i.e. whatever resources we opened as a part of the try block will be closed inside the finally block. Whereas finalize() method is responsible to perform cleanup activities related to the object i.e. whatever resources associated with the object will be deallocated before destroying an object by using finalize() method.

Checked & Unchecked Exceptions

Q25) What is the checked exception?*

The exceptions which are checked by the compiler for smooth execution of the program are called checked exceptions. Example:- FileNotFoundException, SQLException and e.t.c.

Q26) What is an unchecked exception?*

The exceptions which are not checked by the compiler, whether programmers handle them or not. Such types of exceptions are called unchecked exceptions. Example:- ArithmeticException, NullPointerException, and e.t.c.

Q27) What exceptions come under checked and unchecked exceptions?

RuntimeException with its all subclasses, and Error class with all its subclasses comes under unchecked exceptions. The remaining all exceptions come under checked exceptions.

Q28) Difference between checked vs unchecked exception?***

When an exception is thrown by JVM/developer if that exception handling is checked by the compiler then the exception is called a checked exception, else that exception is called an unchecked exception.

Error, RuntimeException, and their subclasses are called unchecked exceptions because this exception handling is not checked by the compiler. It means these exception objects catching or reporting are optional.

Throwable, Exception and its subclasses are called checked exceptions because if they are thrown then the compiler checks their handling and if they are not caught by using catch block or reported to caller method using “throws” keyword then compiler gives compile-time error:- unreported exception must be caught or declared to be thrown.

throw & throws

Q29) What is the purpose of the “throw” keyword?*

The “throw” keyword is used to hand over our created exception object to the JVM manually from a method or constructor. In most cases, we use it for throwing checked exceptions.

Q30) What is the purpose of the “throws” keyword?*

The “throws” keyword is used to report the raised exception to this method caller. It is mandatory to report checked exceptions if they are not caught.

Q31) In a method where should we use “throw” and “throws” keywords?

The throw keyword must be used in method logic, whereas the “throws” keyword must be used in method prototype after method signature.

Q32) Difference between “throw”, “throws” and “thrown”?***

throw:- The “throw” keyword is used to hand over our created exception object to the JVM manually from a method or constructor. In most cases, we use it for throwing checked exceptions. The throw keyword must follow the Throwable type of object, & it must be used only in method logic.

throws:- The “throws” keyword is used to report the raised exception to this method caller. It is mandatory to report checked exceptions if they are not caught. The throws keyword must follow the Throwable type of class name and must be used in the method prototype after the method signature.

thrown:- There is no such type of keyword in Java.

Example of throw & throws:-

public static void m1() throws ArithmeticException {
   // throwing unchecked exception
   throw new ArithmeticException();
}

public static void m2() throws InterruptedException {
   // throwing checked exception
   throw new InterruptedException();
}

Others

Q33) What is exception propagation?

The process of sending an exception from called method to calling method is called exception propagation. Whenever an exception is propagated & that exception is not caught in the calling method then execution of both called and calling method is terminated abnormally.  See More:- Exception Propagation in Java.

Q34) How long an exception is propagated?
Till main() method. Then the main() method propagates it to the JVM.

Q35) What are various methods given in the Throwable class to print exception messages?

The Throwable class contains printStackTrace(), toString(), and getMessage() method to print exception messages. See more:- Different ways to print exception messages in Java.

Q36) What is the exception message format printed by JVM?

The exception message format printed by JVM:- Exception in thread <thread-name> <exception-name> : <reason for the exception> <place of the exception>

Q37) What is the difference between printing exceptions by JVM and printStackTrace() method?
Exceptions printed through JVM contain “thread-name” but the printStackTrace() method doesn’t contain “thread-name”.

Q38) Can we develop checked exceptions?
Yes, we can develop checked exceptions derived from java.lang.Exception class.

// NegativeNumberException.java
public class NegativeNumberException extends Exception {

   // No-arg constructor with super() call
   public NegativeNumberException(){
      super();
   }

   // String-arg constructor with super() call
   public NegativeNumberException(String msg){
      super(msg);
   }
}

See More:- Develop User-defined Custom exception, Java Custom Exception Example

Q39) Can we develop unchecked exceptions?

Yes, we can develop unchecked exceptions derived from java.lang.RuntimeException class. But it is not recommended to develop unchecked exceptions.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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