Table of contents
1.
Introduction
2.
Exception Handling Interview Questions for Freshers
2.1.
1. What is an exception?
2.2.
2. Write the types of Exceptions in Java.
2.3.
3. What are the advantages of using exception handling in your program?
2.4.
4. List the Exception handling keywords in Java.
2.5.
5. Give the difference between error and Exception in Java.
2.6.
6. What are built-in Exceptions?
2.7.
7. Can checked exceptions be thrown from the static block?
2.8.
8. Can we write only try block without a catch and finally blocks?
2.9.
9. What is the exception OutOfMemoryError in Java?
2.10.
10. Will the 'finally' block be executed if either of the 'try' or 'catch' blocks return the control?
3.
Exception Handling Interview Questions for Intermediate
3.1.
11. Write the difference between throw, throws, and throwable in Java.
3.2.
12. Write the difference between final, finally, and finalize in Java.
3.3.
13. What happens if we have statements after the finally block and the control is returning from the finally block itself?
3.4.
14. What do you mean by ClassCastException?
3.5.
15. Do you know try-with-resources blocks? Why do we use them? When are they introduced?
3.6.
16. Can you have an empty catch block?
3.7.
17. What does JVM do when an exception occurs in a program?
3.8.
18. Is it possible to have a return statement in the catch or finally block?
3.9.
19. What is re-throwing an exception?
3.10.
20. What is Exception Propagation?
4.
Exception Handling Interview Questions for Experienced
4.1.
21. Explain User Defined Exceptions. Give an example.
4.2.
Java
4.3.
22. Explain an unreachable catch block error.
4.4.
23. Explain the hierarchy of exceptions in Java.
4.5.
24. Can we throw multiple exceptions in one throw statement?
4.6.
25. What is a chained exception in java?
4.7.
26. What are the methods provided by the Throwable class in Java?
4.8.
27. Explain stack trace in Java. Why is it important in exception handling?
4.9.
28. Mention a few of the best practices in Java exception handling.
4.10.
29. Is it possible to override a superclass method that is throwing an unchecked exception along with a checked exception in the sub class?
4.11.
30. It is always recommended to close the DB resources to keep them inside a finally block. Why?
5.
Frequently Asked Questions
5.1.
What are the different scenarios causing exceptions in Thread Main?
5.2.
What are the 5 keyword exception handling in Java?
5.3.
How do you handle exceptions interview questions?
6.
Conclusion
Last Updated: Dec 16, 2024
Easy

Exception Handling Interview Questions

Author Komal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

This blog consists of 30 Java Exception Handling Interview Questions with a mix of easy, medium, and hard. But, let's familiarise ourselves with the basic concepts of Java before jumping to the Java Exception Handling Interview Questions.

Java Exception Handling is a mechanism that manages runtime errors, ensuring the normal flow of a program. It involves using try-catch blocks, throwing exceptions, and defining custom exceptions to handle and recover from unexpected events and errors during program execution efficiently.

Java Exception Handling Interview Questions

Java is a high-level language developed by James Gosling and was released in 1995 to the world. One of the best features is that it is an object-oriented language and is class-based. It can be used on various platforms and open source. It is a general-purpose language used to compile and run code anywhere. Source files are saved with the extension .java. A java program, after being written, is first compiled into bytecode which produces a file with a .class extension. It is used for mobile applications, desktop applications, and web applications.

Let us now get started with the Java Exception Handling Interview Questions. These Java Exception Handling Interview Questions will help you in cracking interviews. Java Exception Handling Interview Questions form a basic part of any Java Developer Interview. The bunch of Java Exception Handling Interview Questions that we will be looking at in the next section of the blog consists of various random topics and questions about Exceptions.

Exception Handling Interview Questions for Freshers

1. What is an exception?

Exception is an event which disrupts the flow of a program. When an exception occurs, an exception object is created, which contains the information regarding the error, type, and state of the program when the error occurred. Refer to Intro to Exception Handling for more reference.

2. Write the types of Exceptions in Java.

We have two types of exceptions in Java: Checked and Unchecked. Checked exceptions are the exceptions checked at compile time by the compiler. Unchecked Exceptions are those not checked at the compile time by the compiler. 

3. What are the advantages of using exception handling in your program?

Java Exception handling maintains the flow of program execution. It handles the exceptions.

4. List the Exception handling keywords in Java.

There is 5 Exception Handling keywords in Java enlisted:

  • try
  • catch
  • finally
  • throw
  • throws

5. Give the difference between error and Exception in Java.

Difference between error and Exception in Java is errors are all unchecked, but exceptions can be checked or unchecked. Errors occur at the run time, whereas the exceptions occur at the compile time.

6. What are built-in Exceptions?

The exceptions already present in the Java Libraries and can help handle certain error situations are called built-in Exceptions. Examples are ArithmeticException, ArrayIndexOutOfBoundException, etc.

7. Can checked exceptions be thrown from the static block?

Checked Exceptions cannot be thrown from the static block; there's no specific path to catch checked Exceptions.

Must Read Static Blocks In Java.

8. Can we write only try block without a catch and finally blocks?

No, it throws a compilation error. The try block should be followed by either catch or a finally block. Either one of them can be removed but not both.

9. What is the exception OutOfMemoryError in Java?

It is the sub class of java.lang.Error encountered when the JVM runs out of memory.

10. Will the 'finally' block be executed if either of the 'try' or 'catch' blocks return the control?

The finally block is always executed no matter if the try or catch block returns the control. 

Exception Handling Interview Questions for Intermediate

11. Write the difference between throw, throws, and throwable in Java.

Throw keyword in Java is used to throw an exception manually. Exception should be of type java.lang.Throwable class or its subclasses

class ThrowExample{
    void method() throws Exception
    {
        Exception ex = new Exception();
        throw ex;            
    }
}

throws keyword in java is used in the method declaration to indicate that this method may throw exceptions. 

Let's take a look at the example below:

class ThrowsExample
{
    void methodOne() throws SQLException
    {
        //This method may throw SQLException
    }
 
   }

Throwable forms a part of the super class that is for all types of errors and exceptions in java. Let's take a look at the following example.

class MyException extends Throwable
{
           //Customized Exception class
}

12. Write the difference between final, finally, and finalize in Java.

Final is an access modifier. finally, a block in Exception Handling and finalize forms a method of the object class. Moreover, the final method is called when we execute it, finally executed after the try-catch block is executed, and finalize executes just before the object is destroyed.

13. What happens if we have statements after the finally block and the control is returning from the finally block itself?

This gives an unreachable code error. As the control is returning from the finally block itself, the compiler will not look into the statements after it. Hence, it shows an unreachable code error.

14. What do you mean by ClassCastException?

It is a RuntimeException that occurs when JVM is unable to cast an object of one type to another type.

15. Do you know try-with-resources blocks? Why do we use them? When are they introduced?

The try statement that declares one or more resources and ensures that each of them is closed finally at the end of statement execution is called the try-with-resources block.

16. Can you have an empty catch block?

A catch block is used to catch the exceptions found in the try block. Actually, we can have an empty catch block, but there are better practices to implement.

17. What does JVM do when an exception occurs in a program?

An exception Object is created, which is thrown to inform that an error has occurred. If the Exception is not handled correctly, JVM displays an error message and terminates.

18. Is it possible to have a return statement in the catch or finally block?

Yes, we can have a return statement in the catch or finally block; if we write a return statement at the end, the code will execute successfully, and the code below it will become a part of unreachable code.

19. What is re-throwing an exception?

When an exception is found in the catch block, first of all, the Exception is caught by the catch block. Then, the Exception has to be re-thrown. To re-throw an exception, we use the throw keyword.

20. What is Exception Propagation?

Exception propagation is another concept of Java Exception handling. It refers to the transferring of Exceptions from one method to the previous method in order to handle the Exception efficiently.

Exception Handling Interview Questions for Experienced

21. Explain User Defined Exceptions. Give an example.

User Defined Exceptions are the exceptions created by the programmers to use their own designed exceptions and those not present in the java exception library. 

  • Java

Java

class ninjas{
public static void main(String args[]){
try{
int a = 7;
int b = 10;
int f = a / b;
System.out.println(f);
if(f == 0){
throw new MyException1("Designed Exception");
}
}
catch(MyException1 e){
System.out.println(e.getMessage());
}
}
}
class MyException1 extends Exception {
public MyException1(String message){
super(message);
}
}
You can also try this code with Online Java Compiler
Run Code

Output

0
Designed Exception

22. Explain an unreachable catch block error.

As Exception is the superclass of all exceptions, the catch block provided with relation to it should and must always come last. When retaining numerous catch blocks, the catch blocks must be kept in ascending order of specificity. Exception subclasses should always come first, followed by superclasses. The compiler will generate an error if we continue to order superclasses before subclasses.

23. Explain the hierarchy of exceptions in Java.

The hierarchy of exceptions in Java is shown as follows:

  1. java.lang.Error: It is a super class for all types of errors in Java. 
    1. java.lang.VirtualMachineError: –
      • StackOverFlowError
      • OutOfMemoryError
    2. java.lang.AssertionError
    3. java.lang.LinkageError: 
      • NoClassDefFoundError
      • IncompatibleClassChangeError
  2. java.lang.Exception: It is a super class of all exception types in Java. Common 
    1. RunTimeException
      • ArithmeticException
      • NumberFormatException
      • NullPointerException
      • ArrayIndexOutOfBoundsException
      • ClassCastException
    2. java.lang.InterruptedException
    3. java.lang.IOException
    4. java.lang.SQLException
    5. java.lang.ParseException

24. Can we throw multiple exceptions in one throw statement?

Ans: No, we cannot throw multiple exceptions in one throw statement. Only one object of exception type can be thrown by using a throw statement at a time.

25. What is a chained exception in java?

Throwing an exception along with another exception is called a chained exception in java.

26. What are the methods provided by the Throwable class in Java?

The methods provided by the Throwable class are as follows:

  • getMessage()
  • toString()
  • printStackTrace()
  • fillInStackTrace()
  • getStackTrace()
  • getClause()

27. Explain stack trace in Java. Why is it important in exception handling?

A stack trace contains information regarding methods called during your execution of the application. A stack trace is a debugging tool as it helps in the determination of the exact point where the exception occurred in the application and also the reason why it occurred. 

28. Mention a few of the best practices in Java exception handling.

  1. Use a finally block to clean up resources or close them.
  2. Throw specific exceptions.
  3. Do not catch the Exception class. Catch the specific sub classes.
  4. No exception must be thrown from the finally block.
  5.  Use descriptive messages when throwing exceptions.

29. Is it possible to override a superclass method that is throwing an unchecked exception along with a checked exception in the sub class?

When a super class method is throwing an unchecked exception, then it is possible for it to be overridden in the sub class with the same exception or any other unchecked exceptions, but it's not possible to do so with checked exceptions.

30. It is always recommended to close the DB resources to keep them inside a finally block. Why?

The finally block is the block that is always executed no matter whether the exceptions are raised or not or caught. Cleanup Operations ensure that these will always be executed irrespective of whether an exception occurs or not.

Frequently Asked Questions

What are the different scenarios causing exceptions in Thread Main?

Exceptions in the main thread can occur due to:

  • Unhandled runtime errors in the main() method (e.g., NullPointerException, ArithmeticException).
  • Synchronous code failures.
  • Explicitly throwing exceptions without proper handling in the main thread.

What are the 5 keyword exception handling in Java?

In Java, the key exception-handling keywords are: try(used to enclose a block of code), catch(used to catch and handle exceptions), finally(used to define a block of code that will be executed regardless of whether an exception occurred or not), throw(used to explicitly throw an exception), and throws(used in method signatures to indicate that the method might throw specific exceptions, which need to be handled by the caller or propagated further).

How do you handle exceptions interview questions?

Exception handling involves using try to enclose risky code, catch to manage exceptions, finally for cleanup, throw to create exceptions, and throws to indicate potential exceptions in methods. It ensures smoother program execution and error recovery.

Conclusion

We discussed a comprehensive list of 30 Java Exception Handling Interview Questions covering essential concepts, from basics to advanced topics. We hope these Java Exception Handling Interview Questions helped you enhance your knowledge. Exception forms an important topic of Java and hence it’s important to study Exception handling. Refer to the above Java Exception Handling Interview Questions as the collection of the most asked questions in any Java interview regarding Exception Handling.

If you found this blog interesting and insightful, refer to similar blogs:

Live masterclass