Throws, Throw, Finally

Understanding the use of throws, throw, and finally in Java.

Throws, Throw, Finally Interview with follow-up questions

Interview Question Index

Question 1: What is the difference between throw and throws in Java?

Answer:

The 'throw' keyword is used to explicitly throw an exception in Java. It is followed by an instance of an exception class or a subclass of Exception. On the other hand, the 'throws' keyword is used in the method signature to declare that the method might throw one or more exceptions. It is followed by the names of the exception classes that the method can throw.

Back to Top ↑

Follow up 1: Can you provide an example where we use 'throw' keyword?

Answer:

Sure! Here's an example:

public class Example {
    public static void main(String[] args) {
        try {
            throw new Exception("This is an example exception");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

In this example, we use the 'throw' keyword to explicitly throw an exception of type Exception. The catch block then catches the exception and prints its message.

Back to Top ↑

Follow up 2: In what scenarios 'throws' keyword is used?

Answer:

The 'throws' keyword is used in the method signature to declare that the method might throw one or more exceptions. It is used when a method wants to indicate that it can potentially encounter an exception, but it does not handle the exception itself. Instead, it delegates the responsibility of handling the exception to the caller of the method.

Back to Top ↑

Follow up 3: Can we throw multiple exceptions in Java?

Answer:

Yes, we can throw multiple exceptions in Java. When throwing multiple exceptions, we can either use multiple 'throw' statements or use a single 'throw' statement with a comma-separated list of exceptions. Here's an example:

public class Example {
    public static void main(String[] args) throws Exception1, Exception2 {
        if (condition) {
            throw new Exception1();
        } else {
            throw new Exception2();
        }
    }
}

In this example, depending on the condition, we throw either Exception1 or Exception2.

Back to Top ↑

Follow up 4: What happens if we don't handle the exception thrown by a method?

Answer:

If we don't handle the exception thrown by a method, it will propagate up the call stack until it is either caught and handled by a try-catch block or it reaches the top-level of the program where it can cause the program to terminate. If the exception is not caught and handled, it will result in an unhandled exception error and the program will terminate.

Back to Top ↑

Question 2: What is the purpose of finally block in Java?

Answer:

The purpose of the finally block in Java is to define a section of code that will be executed whether an exception is thrown or not. It is used to perform cleanup actions, such as closing resources (e.g. files, database connections) or releasing locks, that need to be done regardless of whether an exception occurs or not.

Back to Top ↑

Follow up 1: Is it mandatory to use finally block with try-catch?

Answer:

No, it is not mandatory to use a finally block with try-catch. However, if a finally block is present, it will always be executed, regardless of whether an exception is thrown or not. It is recommended to use a finally block when there are resources that need to be cleaned up, to ensure they are properly released.

Back to Top ↑

Follow up 2: What happens if we don't have a catch block but only a finally block?

Answer:

If there is no catch block but only a finally block, and an exception is thrown within the try block, the exception will not be caught and will propagate up the call stack. The finally block will still be executed before the exception propagates, allowing for cleanup actions to be performed. If no exception is thrown, the finally block will still be executed.

Back to Top ↑

Follow up 3: Can we use a return statement in a finally block?

Answer:

Yes, we can use a return statement in a finally block. However, it is important to note that if a return statement is encountered in the finally block, it will override any return statement in the try or catch block. The value returned will be the one specified in the finally block.

Back to Top ↑

Follow up 4: What happens if an exception is thrown in finally block?

Answer:

If an exception is thrown in the finally block, it will override any exception that was previously thrown in the try or catch block. The new exception will propagate up the call stack, and any remaining code in the try or catch block will not be executed. It is generally not recommended to throw exceptions from the finally block, as it can lead to unexpected behavior and make debugging more difficult.

Back to Top ↑

Question 3: Can we catch multiple exceptions in a single catch block?

Answer:

Yes, we can catch multiple exceptions in a single catch block by using the | (pipe) operator to separate the exception types. For example:

try {
    // code that may throw exceptions
} catch (ExceptionType1 | ExceptionType2 | ExceptionType3 e) {
    // exception handling code
}
Back to Top ↑

Follow up 1: How can we catch multiple exceptions in a single catch block?

Answer:

To catch multiple exceptions in a single catch block, we can use the | (pipe) operator to separate the exception types. Here's an example:

try {
    // code that may throw exceptions
} catch (ExceptionType1 | ExceptionType2 | ExceptionType3 e) {
    // exception handling code
}
Back to Top ↑

Follow up 2: What is the advantage of catching multiple exceptions in a single catch block?

Answer:

Catching multiple exceptions in a single catch block can make the code more concise and readable. It reduces code duplication and allows for a unified exception handling logic for multiple exception types. This can simplify the code and improve maintainability.

Back to Top ↑

Follow up 3: Can we catch a parent exception before a child exception?

Answer:

No, we cannot catch a parent exception before a child exception. In Java, when catching exceptions, the catch blocks are evaluated in the order they appear. If a catch block for a parent exception is placed before a catch block for a child exception, the child exception will never be caught because the parent catch block will handle it first.

Back to Top ↑

Follow up 4: What happens if we catch a parent exception before a child exception?

Answer:

If we catch a parent exception before a child exception, the catch block for the parent exception will handle both the parent and child exceptions. The catch block for the child exception will never be executed because the parent catch block will handle it first. This can lead to unexpected behavior and may not be desirable in most cases.

Back to Top ↑

Question 4: What is the use of throw keyword in Java?

Answer:

The throw keyword in Java is used to explicitly throw an exception. It is used to indicate that a specific exception has occurred and the program should handle it accordingly.

Back to Top ↑

Follow up 1: Can we throw an exception manually?

Answer:

Yes, we can throw an exception manually using the throw keyword. By using the throw keyword, we can throw any exception object that is a subclass of the Throwable class.

Back to Top ↑

Follow up 2: What is the syntax to throw an exception?

Answer:

The syntax to throw an exception in Java is as follows:

throw new ExceptionType("Exception message");
Back to Top ↑

Follow up 3: Can we throw a checked exception from a method?

Answer:

Yes, we can throw a checked exception from a method. However, if a method throws a checked exception, it must declare the exception using the throws keyword in its method signature. The calling method must handle the exception or declare it using the throws keyword as well.

Back to Top ↑

Follow up 4: What happens if we throw an exception from a method but don't catch it?

Answer:

If an exception is thrown from a method but not caught, it will propagate up the call stack until it is caught by an appropriate catch block or until it reaches the top-level of the program. If the exception is not caught at any level, the program will terminate and an error message will be displayed.

Back to Top ↑

Question 5: What is the role of finally block when an exception is thrown?

Answer:

The finally block is used to specify a block of code that will be executed regardless of whether an exception is thrown or not. It is typically used to release resources or perform cleanup operations that need to be done regardless of the outcome of the try-catch block.

Back to Top ↑

Follow up 1: Can we have a try block without catch or finally block?

Answer:

Yes, we can have a try block without a catch or finally block. However, if a try block is used without a catch block, then a finally block must be present to handle any exceptions that may occur. If a finally block is not present, the code will not compile.

Back to Top ↑

Follow up 2: Does finally block always execute?

Answer:

Yes, the finally block always executes, regardless of whether an exception is thrown or not. It ensures that the specified code is executed even if an exception occurs or if there is an early return statement in the try or catch block.

Back to Top ↑

Follow up 3: What happens to the finally block if we use System.exit() in try or catch block?

Answer:

If the System.exit() method is called in the try or catch block, the JVM will terminate and the finally block will not be executed. This is because the System.exit() method terminates the JVM and all subsequent code is not executed.

Back to Top ↑

Follow up 4: What is the order of execution of try, catch and finally blocks?

Answer:

The order of execution of try, catch, and finally blocks is as follows:

  1. The code inside the try block is executed.
  2. If an exception occurs, the catch block(s) are checked to see if they can handle the exception. If a matching catch block is found, the code inside the catch block is executed.
  3. If a catch block is not found or if the catch block(s) cannot handle the exception, the finally block is executed.
  4. After the finally block is executed, the exception is propagated up the call stack.
Back to Top ↑