Exception Handling Interview Questions for Freshers
DeveloperCorners

Exception Handling Interview Questions for Freshers

Exception Handling in Java

 Book Reference: https://www.tutorialspoint.com/ebook/java-the-important-reference-1-0/index.asp


Introduction

An Exception refers to abnormal behaviour of an application that occurs at the time of execution that could lead to the termination of that application if not handled. Exceptions could include sudden network errors, database connection errors, errors due to non-existent or corrupt files, logical errors that were not handled by the developers and many more. Java provides a great way of handling Exceptions that results in a robust application that does not fail in case of abnormalities. Due to its importance, exception handling has become a very important and favourite topic amongst interviewers. Every software developer should know how to handle unexpected errors while developing an application.

In this article, we will go through the commonly asked Exception-Handling Interview Questions for both freshers and experienced software developers:

Exception Handling Interview Questions for Freshers

 

1. What is an exception in Java?

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 is exception handling in Java and what are the advantages of exception handling?

Exception Handling is the technique of handling unexpected failures that could occur in a program so that the program does not terminate and normal execution flow is maintained. Consider an example program where we have 6 statement blocks as shown in the below image. Statements 1 and 2 execute successfully. While executing the statement 3 block, an unexpected error occurred. Now the Java program checks if there is any exception-handling mechanism present. If an exception handling block is present, then the exception is handled gracefully and the program continues with the execution of the statement 4 block. If not, the program gets terminated.

 

The following are some of the Advantages of using Exception Handling in Java:

  1. The most important advantage of having an exception-handling technique is that it avoids abnormal program termination and the normal flow of the program is maintained.
  2. Provides flexibility to the programmers to define/handle what should occur in cases of failures/errors thereby making the applications more robust and immune to unexpected scenarios.
  3. Provides stable user experience in cases of failures by providing means to let the user know what made the program fail.

3. How are exceptions handled in Java?

In Java, exceptions could be handled in the following ways:

  1. try-catch block: The try section holds the code that needs to be normally executed and it monitors for any possible exception that could occur. The catch block “catches” the exception thrown by the try block. It could consist of logic to handle failure scenario or the catch block could simply rethrow the exception by using the “throw” keyword.
  2. finally block: Regardless of whether an exception has occurred or not, if we need to execute any logic, then we place it in the final block that is usually associated with the try-catch block or just with the try block. The final block is not executed when System.exit(0) is present in either the try or catch block.

Consider an example where we need to get the value of the score from a file called “resultFile”. When we access the file, the file could exist and we get the score and everything happens normally. But there could be cases where the file was accidentally deleted. In this case, when the program tries to access that file, then it throws FileNotFoundException. There are 2 ways to handle this exception (Depending on the requirements, we need to choose what way is the most appropriate for us):-

  • Case 1: Throw IllegalArgumentException stating the file does not exist as shown in the logic below.
public int getResultScore(String resultFile) {
    try {
        Scanner fileContents = new Scanner(new File(resultFile));
        return Integer.parseInt(contents.nextLine());
    } catch (FileNotFoundException fileNotFound) {
        // handle exception by throwing a new exception
        throw new IllegalArgumentException("Result file does not exist");
    }
}
  • Case 2: Return the score as 0 and log the error that file doesn’t exist as shown in the logic below.
public int getResultScore(String resultFile) {
    try {
        Scanner fileContents = new Scanner(new File(resultFile));
        return Integer.parseInt(contents.nextLine());
    } catch (FileNotFoundException fileNotFound) {
        // handle exception by returning 0 and logging error
        logger.error("Result file does not exist");
        return 0;
    }
}

Finally, irrespective of whether the code running normally or not, we would want to close the resources. This could run in the finally block as shown below:

public int getResultScore(String resultFile) {
    Scanner fileContents;
    try {
        fileContents = new Scanner(new File(resultFile));
        return Integer.parseInt(contents.nextLine());
    } catch (FileNotFoundException fileNotFound) {
        // handle exception by returning 0 and logging error
        logger.error("Result file does not exist");
        return 0;
    } finally {
        if (fileContents != null) {
            fileContents.close();
        }
    }
}

Note:

As of Java 7, the new feature “try-with-resources” helps to autoclose the resources that extend the “AutoCloseable” interface. The close() method will be called when it exits the try-with-resources block. For example, the above code which has a close() method call could be simplified as shown below:

public int getResultScore(String resultFile) {
    try (Scanner fileContents = new Scanner(new File(resultFile))) {
      return Integer.parseInt(contents.nextLine());
    } catch (FileNotFoundException e ) {
        // handle exception by returning 0 and logging error
        logger.error("Result file does not exist");
        return 0;
    }
}
  • Sometimes, the program could throw more than 1 exception. In this case, Java supports the usage of multiple catch blocks. Our example could also encounter a NumberFormatException exception while parsing integer numbers and this could be handled as shown below:
public int getPlayerScore(String playerFile) {
    try (Scanner fileContents = new Scanner(new File(resultFile))) {
        return Integer.parseInt(contents.nextLine());
    } catch (FileNotFoundException e ) {
        // If an exception occurs while opening the file
        logger.error("Result file does not exist");
        return 0;
    } catch (NumberFormatException e) {
        // If an exception occurs during parsing the contents to integer format
        logger.error("Couldn't format number", e);
        return 0;
    }
}
  • Multiple catch blocks are useful if we have different exception-handling logic for different types of exceptions. If our logic of handling the exception is the same (as in the above scenario), then Java7 introduced the feature to union the catch blocks - handle multiple exceptions in the same catch block. The above could now be simplified to:
 public int getPlayerScore(String playerFile) {
   try (Scanner fileContents = new Scanner(new File(resultFile))) {
       return Integer.parseInt(contents.nextLine());
   } catch (FileNotFoundException | NumberFormatException e ) {
       //e.getMessage() prints the detailed message 
       logger.error("Score couldn't be loaded - " + e.getMessage()); 
       return 0;
   } 
}

 


4. What is exception propagation in Java?

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. The same has been represented in the image below:

 

5. 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.

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

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

The throw keyword allows a programmer to throw an exception object to interrupt normal program flow. The exception object is handed over to the runtime to handle it. For example, if we want to signify the status of a task is outdated, we can create an OutdatedTaskException that extends the Exception class and we can throw this exception object as shown below:

if (task.getStatus().equals("outdated")) {
    throw new OutdatedTaskException("Task is outdated");
}

The throws keyword in Java is used along with the method signature to specify exceptions that the method could throw during execution. For example, a method could throw NullPointerException or FileNotFoundException and we can specify that in the method signature as shown below:

public void someMethod() throws NullPointerException, FileNotFoundException {
    // do something
}

 

8. How do you handle checked exceptions?

Checked Exceptions can be handled by either using a try-catch block or by using the throws clause in the method declaration. If these exceptions are not handled properly, then the program would fail to compile.

9. Differentiate between Checked Exception and Unchecked Exceptions in Java.

The followings programs are the differences between Checked and Unchecked Exceptions:

Checked Exceptions

Unchecked Exceptions

These exceptions are checked and handled at the time of compilation.

These Exceptions are not checked and handled at compilation time. They occur during the runtime of the program and can not be anticipated by the compiler.

These exceptions are a direct subclass of the Exception class.

These exceptions are a direct subclass of the RuntimeException class.

Program would give compilation error if checked exceptions are not handled.

Program compiles successfully, but the exception could occur at runtime due to logical errors in the program.

Checked Exceptions require handling using a try-catch block or at least the method should use the throws keyword to let the calling method know that a checked exception could be thrown from this method.

Unchecked Exceptions do not require try-catch or throws handling. These exceptions could occur due to mistakes in programming logic.

Examples: IOException, FileNotFoundException, DataAccessException, InterruptedException, etc.

Examples: ArithmeticException, ArrayIndexOutOfBoundException, NullPointerException, InvalidClassException, etc.

 

10. Can you catch and handle Multiple Exceptions in Java?

There are three ways to handle multiple exceptions in Java:

  • Since Exception is the base class for all exception types, make use of a catch block that catches the Exception class-
try {
    // do something
} catch (Exception exception) {
    // handle exception
}

However, it is recommended to use accurate Exception handlers instead of generic ones. This is because having broad exception handlers could make the code error-prone by catching exceptions that were not anticipated in the software design and could result in unexpected behavior.

  • From Java 7 onwards, it is now possible to implement multiple catch blocks as shown below -
    try {
       // do something
    } catch (FileNotFoundException fileNotFoundException) {
        // handle FileNotFoundException
    } catch (EOFException eofException) {
        // handle EOFException
    } 

When we are using multiple catch blocks, we need to ensure that in a case where the exceptions have an inheritance relationship, the child exception type should be the first and the parent type later to avoid a compilation error.

  • Java 7 also began to provide the usage of multi-catch blocks for reducing duplication of code if the exception handling logic was similar for different exception types. The syntax of the multi-catch block is as shown below-
try {
    // ...
} catch (FileNotFoundException | EOFException exception) {
    // ...
}

11. What is a stack trace and how is it related to an Exception?

A stack trace is information consisting of names of classes and methods that were invoked right from the start of program execution to the point where an exception occurred. This is useful to debug where exactly the exception occurred and due to what reasons. Consider an example stack trace in Java,

Exception in thread "main" java.lang.NullPointerException
        at com.example.demoProject.Book.getBookTitle(Book.java:26)
        at com.example.demoProject.Author.getBookTitlesOfAuthor(Author.java:15)
        at com.example.demoProject.DemoClass.main(DemoClass.java:14)

To determine where an exception has occurred, we need to check for the beginning of the trace that has a list of “at …”. In the given example, the exception has occurred at Line Number 26 of the Book.java class in the getBookTitle() method. We can look at this stack trace and go to the method and the line number mentioned in the trace and debug for what could have caused the NullPointerException. Furthermore, we can get to know that the getBookTitle() method in the Book.java class was called by the getBookTitlesOfAuthor() method in the Author.java class in Line Number 15 of the file and this in turn was called by the main() method of the DemoClass.java file in Line Number 14.

12. 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.

13. Can we have statements between try, catch and finally blocks?

No. This is because they form a single unit.

14. How are the keywords final, finally and finalize different from each other?

  • final keyword: By using this keyword,
  • we can declare a variable as final (meaning, variable value cannot be changed).
  • we can declare a method as final (meaning, that method cannot be overridden).
  • we can declare a class as final (meaning, that class cannot be extended).
  • finally keyword: This is used in conjunction with the try-catch block or the try block where we want to run some logic whether or not an exception has occurred.
  • finalize keyword: This is a method called by the Garbage Collector just before destroying the objects no longer needed in the program.

15. What is the output of this below program?

public class TestClass 
{
    public static void main(String[] args) 
    {
        int a = 30;
        int b = 40;
        int c = 10;
        int expression = (a * b)/(a - b + c);
        System.out.println("Result: " +expression);
      }
}

When the expression is evaluated, the denominator becomes zero. Hence Java would throw ArithmeticException when it’s executed. The exception logs would be:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestClass.main(TestClass.java:8)

 

16. What is the difference between ClassNotFoundException and NoClassDefFoundError?

Both these exceptions occur when ClassLoader or JVM is not able to find classes while loading during run-time. However, the difference between these 2 are:

  • ClassNotFoundException: This exception occurs when we try to load a class that is not found in the classpath at runtime by making use of the loadClass() or Class.forName() methods.
  • NoClassDefFoundError: This exception occurs when a class was present at compile-time but was not found at runtime.

17. What do you understand by an unreachable catch block error?

This error is thrown by the compiler when we have multiple catch blocks and keep parent classes first and subclasses later. The catch blocks should follow the order of the most specific ones at the top to the most general ones at the bottom. If this is not followed, an unreachable catch block error is thrown during compile time.

要查看或添加评论,请登录

?????????????? ??????????????????的更多文章

  • Importance of LinkedIn: 7 Benefits to Polish Your Profile

    Importance of LinkedIn: 7 Benefits to Polish Your Profile

    Importance of LinkedIn: 7 Benefits to Polish Your Profile You've heard LinkedIn is important, but is it? And if so…

    5 条评论
  • What is Hibernate in Java? & Hibernate Interview Questions

    What is Hibernate in Java? & Hibernate Interview Questions

    What is Hibernate in Java? & Hibernate Interview Questions Hibernate is a Java-based persistence framework and an…

    3 条评论
  • Classloaders In Java

    Classloaders In Java

    Understand Classloading: Types Of Classloaders In Java 7 Types Of Class Loaders In Java In this article, we’ll…

  • 5 Basic concepts in programming languages for better coding skills

    5 Basic concepts in programming languages for better coding skills

    5 basic Concepts in programming languages for better coding skills Programming languages are the foundation of modern…

    2 条评论
  • Object-Oriented Programming (OOP) languages (Features & Advantages)

    Object-Oriented Programming (OOP) languages (Features & Advantages)

    Object-Oriented Programming (OOP) languages! (Features & Advantages) Object-Oriented Programming (OOP) is a programming…

  • What is Git?

    What is Git?

    What is Git? Git is a DevOps tool that is used as a version-control system for tracking the changes happening in system…

    2 条评论
  • Spring Boot Framework

    Spring Boot Framework

    What is Spring Boot? Spring Boot is a Framework from “The Spring Team” to ease the bootstrapping and development of new…

    2 条评论
  • Java Interview Questions for Freshers & Experienced

    Java Interview Questions for Freshers & Experienced

    Java Interview Questions for Freshers & Experienced Book Reference: https://www.tutorialspoint.

    2 条评论
  • What is Chat GPT ? & Use Of Chat GPT.

    What is Chat GPT ? & Use Of Chat GPT.

    What is Chat GPT ? & Use Of Chat GPT. Chat GPT-4 is a large-scale, multimodal model which can accept image and text…

    2 条评论
  • Java Multiple-Choice Questions

    Java Multiple-Choice Questions

    Java Multiple-Choice Questions Book Reference : https://www.tutorialspoint.

社区洞察

其他会员也浏览了