Throws, Throw, Finally


Throws, Throw, Finally Interview with follow-up questions

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

They look similar but do opposite jobs:

  • throw — a statement that actually raises an exception at runtime. It takes a single Throwable instance.
  • throws — a clause in a method signature that declares the checked exceptions a method might raise, pushing the handling responsibility to callers.
// throws — declaration
void readConfig(String path) throws IOException {
    if (path == null)
        throw new IllegalArgumentException("path required");   // throw — action
    ...
}
throw throws
What raises an exception now declares possible exceptions
Where inside a method body in the method signature
Takes one exception instance one or more exception types (comma-separated)
Count one at a time multiple

The points interviewers reward: you can throw any Throwable, but if it's a checked exception you must also throws-declare it (or catch it). throws is only required for checked exceptions — unchecked ones don't need declaring (though you may document them). And when wrapping/rethrowing, preserve the cause: throw new ServiceException("failed", e);. Mnemonic: throw = do it; throws = warn about it.

↑ Back to top

Follow-up 1

Can you provide an example where we use 'throw' keyword?

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.

Follow-up 2

In what scenarios 'throws' keyword is used?

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.

Follow-up 3

Can we throw multiple exceptions in Java?

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.

Follow-up 4

What happens if we don't handle the exception thrown by a method?

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.

2. What is the purpose of finally block in Java?

The finally block defines code that always runs after the try (and any catch) — whether the try completes normally, throws an exception, or even returns. Its purpose is guaranteed cleanup: releasing resources, closing connections, unlocking locks — work that must happen regardless of outcome.

Lock lock = ...;
lock.lock();
try {
    doWork();
} finally {
    lock.unlock();      // always released, even if doWork() throws
}

The gotchas interviewers probe:

  • finally runs even if try/catch has a return — but avoid return/throw inside finally, as it overrides the original return value or swallows the pending exception (a classic bug).
  • It does not run only on System.exit() or a JVM crash.

The crucial 2026 update: for closing resources, prefer try-with-resources (Java 7+) over a manual finally. Any resource implementing AutoCloseable is closed automatically, in reverse order, even on exception — and it correctly handles suppressed exceptions (if both the body and close() throw):

try (var conn = dataSource.getConnection();
     var stmt = conn.prepareStatement(sql)) {
    stmt.execute();
}   // conn and stmt auto-closed — no finally needed

So finally is still right for non-resource cleanup (unlocking, restoring state), but try-with-resources is the modern idiom for closing resources, eliminating most hand-written finally blocks and their bugs.

↑ Back to top

Follow-up 1

Is it mandatory to use finally block with try-catch?

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.

Follow-up 2

What happens if we don't have a catch block but only a finally block?

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.

Follow-up 3

Can we use a return statement in a finally block?

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.

Follow-up 4

What happens if an exception is thrown in finally block?

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.

3. Can we catch multiple exceptions in a single catch block?

Yes — since Java 7, multi-catch lets one catch block handle several exception types, separated by the | operator. It removes duplicated handling code:

try {
    process();
} catch (IOException | SQLException e) {     // handle both the same way
    log.error("operation failed", e);
    throw new ServiceException(e);
}

The rules and gotchas interviewers want:

  • The caught types must not be in a subclass/superclass relationship with each other (e.g. you can't write IOException | FileNotFoundExceptionFileNotFoundException is already an IOException); the compiler rejects redundant types.
  • The variable (e) is implicitly final in a multi-catch.
  • Its static type is the common supertype, so inside the block you can only call methods common to all caught types.

When the handling logic differs per exception, use separate catch blocks instead (ordered most specific first — a broader type before a narrower one is a compile error). Before Java 7, the only option was either duplicating code in multiple catches or catching a broad Exception (which is discouraged). Multi-catch keeps handlers DRY while staying specific — the idiomatic choice when several exceptions share the same response.

↑ Back to top

Follow-up 1

How can we catch multiple exceptions in a single catch block?

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
}

Follow-up 2

What is the advantage of catching multiple exceptions in a single catch block?

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.

Follow-up 3

Can we catch a parent exception before a child exception?

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.

Follow-up 4

What happens if we catch a parent exception before a child exception?

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.

4. What is the use of throw keyword in Java?

The throw keyword explicitly raises an exception at runtime. You give it an exception instance (any Throwable), and execution immediately stops in the current method and unwinds the stack looking for a matching catch (or propagates out).

void withdraw(double amount) {
    if (amount <= 0)
        throw new IllegalArgumentException("amount must be positive");
    if (amount > balance)
        throw new InsufficientFundsException(balance, amount);   // custom exception
    balance -= amount;
}

Common uses interviewers want: validating arguments/state and failing fast (IllegalArgumentException, IllegalStateException, Objects.requireNonNull), signaling domain errors with your own exception types, and rethrowing/wrapping a caught exception while preserving its cause:

catch (SQLException e) {
    throw new DataAccessException("save failed", e);   // wrap, keep cause
}

Points worth adding: you can throw checked or unchecked exceptions, but throwing a checked one means the method must throws-declare it (or catch it). Always include a clear message and, when wrapping, the original cause so the stack trace isn't lost. Prefer specific exception types over a generic RuntimeException. Mnemonic: throw performs the action; throws merely declares the possibility.

↑ Back to top

Follow-up 1

Can we throw an exception manually?

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.

Follow-up 2

What is the syntax to throw an exception?

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

throw new ExceptionType("Exception message");

Follow-up 3

Can we throw a checked exception from a method?

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.

Follow-up 4

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

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.

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

When an exception is thrown inside a try, the finally block still runs — after the matching catch (if any) executes, or, if no catch matches, just before the exception propagates up the stack. That guarantee is exactly why finally is used for cleanup that must happen regardless of success or failure (closing resources, unlocking, restoring state).

Connection conn = open();
try {
    conn.execute(sql);          // throws
} catch (SQLException e) {
    log.error("query failed", e);
} finally {
    conn.close();               // runs whether or not an exception was thrown
}

The gotchas interviewers probe:

  • finally runs even when try/catch does a return or throw — the cleanup happens first, then control transfers.
  • Don't return or throw from finally — it will override the original return value or swallow the in-flight exception, hiding the real failure (a notorious bug).
  • It does not run only if the JVM exits (System.exit) or is killed.

The modern best practice: for resource cleanup, prefer try-with-resources over a manual finally. It auto-closes AutoCloseable resources even when an exception is thrown, in reverse order, and correctly records suppressed exceptions (when both the body and close() fail) — avoiding the subtle bugs of hand-written finally. Reserve finally for non-resource cleanup like releasing a lock or resetting state.

↑ Back to top

Follow-up 1

Can we have a try block without catch or finally block?

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.

Follow-up 2

Does finally block always execute?

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.

Follow-up 3

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

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.

Follow-up 4

What is the order of execution of try, catch and finally blocks?

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.

Live mock interview

Mock interview: Throws, Throw, Finally

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.