June 28, 2022

Java Exception Handling Interview Questions And Answers

In this post there is a collection of Java exception handling interview questions and answers which’ll be helpful for interview preparation.

Java Exception Handling Interview Questions

  1. What is Exception?

    An exception can be defined as a condition that disrupts the normal flow of your code. Since exception happens at run time the current code processing can not continue, it needs to handle that exception that’s where the exception handler mechanism takes over.

    Read more about Exception here.

  2. What is error?

    Error and its subclasses define exceptions that your program cannot handle, like out of memory error. As example– StackOverflowError, OutOfMemoryError.

  3. How does exception handling works in Java?

    When an exceptional condition happens in any method the procedure for exception handling in Java is as follows-

    • An exception object which encapsulates the information about the error, type of the exception, where exception happened is created.
    • The execution of the code in the method is stopped and created exception is thrown.
    • The exception handling mechanism looks for the exception handler that can handle the thrown exception. The method where exception is thrown may handle that exception itself or leave it to the calling method to handle it.
    • If no exception handler is provided for the thrown exception, default exception handler will be called to handle that exception. Default exception handler prints the stack trace from the point exception was thrown and terminates the program.
    Read more about Exception here.
  4. How is exception handling managed in Java?

    Exception handling in Java is managed using 5 keywords- try, catch, finally, throw and throws.

  5. Which is the parent class of all the exception classes in Java?

    Throwable class is the parent class of all the exception classes in Java.

  6. Explain exception hierarchy in Java?

    Throwable class is the parent class of all the exception classes in Java. Just below Throwable in Java exception hierarchy are two subclasses that divide exception into two different branches. These subclasses are Exception and Error.

    See Exception hierarchy here.
  7. What are the advantages of Exception handling in Java?

    Exception handling in Java provides a mechanism to gracefully recover from run time errors.

    Provides better design by separating the code that has your logic from the code that handles exception.

  8. How do you handle exception in your code

    By using a try-catch block. Enclose your code, that might throw an exception, in try block. A catch block is used to handle the exception thrown in the try block.

    try {
    // Code that may throw excpetion
    }
    catch (ExceptionType exp){
    // Exception handler for ExceptionType
    }
    
    Read more about try-catch block here.
  9. What is finally block?

    When an exception is thrown in a code the normal execution flow of the method is disrupted and that may result in opened resources never getting closed. In such scenarios you do need a clean up mechanism that’s where finally block in Java helps.

    A try-catch-finally block in Java has the following form–

    try {
    // Code that may throw excpetion
    }
    catch (ExceptionType exp){
    // Exception handler for ExceptionType
    }
    finally{
    // code that has to be executed after try block completes
    }
    
    Read more about finally block here.
  10. Can we have a try block without catch block?

    Yes we can have a try block without a catch block but in that case try block should be followed by a finally block. try block must be followed by either catch or finally or both.

    Read more about try-catch block here.
  11. Will a finally block execute if no error is thrown in the try block?

    Finally block in Java always executes whether exception is thrown in try block or not.

    Read more about finally block here.
  12. What happens if the exception is thrown in the finally block?

    If code enclosed in try block throws an exception and the finally block also throws an exception then exception thrown by finally clause masks the exception thrown in try block.

  13. What if there is a return statement in try block and no exception is thrown, in such case will finally block be executed?

    Even if there is a return statement in try block and no exception is thrown in try block, finally block will still be executed before the method returns.

  14. When is Java finally block not executed?

    If the JVM exits while the try or catch code is being executed (System.exit() or JVM crash), then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute.

    Read more about finally block here.
  15. What is nested try statement?

    In a nested try one try-catch block resides with in an outer try-catch block. In case an exception occurs in an inner try and no catch block is found to handle the exception of that type, next (outer) try statement is checked for an exception handler and so on.

    Read more about nested try statement here.
  16. Can we have multiple catch blocks after the try block.

    Yes there can be multiple catch blocks after a try block. If an exception is thrown the exception-handling mechanism looks for the catch block with an argument that matches the type of the exception thrown. Only the matching catch clause out of the multiple catch blocks is executed.

    Read more about multiple catch blocks here.
  17. When can you get unreachable code compilation error in reference to multiple catch blocks?

    With multiple catch blocks you will have to ensure that any exception superclass doesn’t come before its exception sub-classes. Placing a catch statement having sub-class as an argument after the catch statement with super class as argument would mean the catch statement with sub-class is unreachable resulting in unreachable code error.

    catch(Exception exp){
      exp.printStackTrace();
    }catch(ArithmeticException exp){
      exp.printStackTrace();
    }
    

    Since Exception class is super class of ArithmeticException exception so placing that catch statement first will result in unreachable code compile time error.

  18. What is throw keyword in Java OR how can you throw an exception manually from the code?

    You can throw an exception explicitly in your Java code, that can be done using throw keyword in Java.

    throw throwableObj;
    

    Here throwableObj must be an instance of Throwable class or any of its subclass.

    Read more about throw keyword in Java here.
  19. Can you rethrow the thrown exception?

    Yes you can rethrow the exception that is caught in a catch block. If the catch block that is catching the exception is not handling it then you can rethrow that exception, using throw keyword, to be caught by an exception handler that can handle it.

    For example-
    catch(Exception exp){
      System.out.println("Exception occurred while dividing" + exp.getMessage());
      throw exp;
    }
    

    Here super class Exception is catching the exception so you can rethrow it to be caught by specific exception handler.

    You can also choose to rethrow the different exception from the thrown exception.

    For example-
    catch(SQLException ex){
      throw new RuntimeException("Error in DB layer", ex);
    }
  20. What is throws Clause in Java?

    You can specify the exceptions that are not handled in the method along with the method declaration. That way you are leaving it to calling method to provide exception handling mechanism for those exceptions.

    type methodName(parameters) throws exception1, excpetion2...{
       ...
       ...
    }
    

    It is mandatory to specify all the checked exception using throws clause in your method declaration if exceptions are not handled with in the method.

    Read more about throws clause in Java here.
  21. What are checked and unchecked exceptions in Java?

    There are three types of exceptions in Java exception handling-

    • Checked Exceptions– These are the exceptions that a code should be able to anticipate and recover from. Java compiler would even force you to put the code that is anticipated to throw checked exception with in a try-catch block or specify it using throws.
    • Error– These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
    • Runtime exceptions– These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from.

    Errors and runtime exceptions are collectively known as unchecked exceptions.

    Read more about checked and unchecked exception here.
  22. What is exception Propagation in Java?

    When an exception is thrown in the method it may be handled in that method or it may be passed on to be handled by other methods in the caller stack. This process of going through the method call stack to look for an exception handler that can handle the thrown exception is known as exception propagation in Java.

    Read more about exception propagation here.
  23. Is there any thing wrong with the following code.
    // Parent class
    class Read {
      public void readFile() throws IOException{
        System.out.println("read file");
      }
    }
    // child class
    public class FileRead extends Read {
      // Overridden method
      public void readFile() throws Exception{
        File file = new File("D://test.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
      }
    ...
    ...
    }
    

    Yes this code will give error at compilation "Exception is super type of IOException." It is because of the rule that the Subclass overridden method can declare any child exception of the exception declared in the parent class method. But it can’t declare any exception higher in the hierarchy.

    Read more about exception handling rules with reference to method overriding here.
  24. What is chained exception in Java?

    Using chained exception in Java you can associate one exception with another. Chained exception helps in the scenario where one exception causes another exception.

    Read more about chained exception here.
  25. What is multi-catch exception in Java?

    Using Multi-catch statement added in Java 7 single catch block can handle more than one type of exception. That way you can avoid duplication of code and also the tendency to use Exception class as a catch-all clause which will hide the real cause.

    In multi-catch statement you need to separate each exception type in the catch clause using the pipe (|) symbol.

    General form-
    catch(Exception Type 1 | Exception Type 2 ex){
      ...
      ...
    }
    
    Read more about multi-catch exception here.
  26. What is try-with-resources in Java?

    try-with-resources, available Java 7 on wards, facilitates automatic resource management. With this feature, try-with-resources in Java, one or more resources are declared with the try statement itself. The try-with-resources statement ensures that the declared resources are closed automatically at the end.

    With try-with-resources you don't need a separate finally block just for closing resources.

    Read more about try-with-resources here.
  27. What is AutoCloseable interface?

    Resources are closed automatically using try-with-resources in Java because of the interface java.lang.AutoCloseable introduced in Java 7. Any object that implements java.lang.AutoCloseable interface can be used as a resource with try-with-resource.

  28. What is suppressed exception with try-with-resource?

    If an exception is thrown from a try block and an exception is thrown from a try-with-resource statement too then the exception thrown by try-with-resource statement is suppressed and the exception thrown by the try block is returned.

  29. How can you create custom exception class in Java?

    See how to create custom exception class in Java here.

That's all for the topic Java Exception Handling Interview Questions And Answers. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment