Friday, 4 April 2025

Java interview questions on throw and throws 


1️⃣ Can we use throw and throws together in the same method?

Answer: Yes, we can use both throw and throws in the same method.

🔹 throws is used in the method signature to indicate that the method may throw an exception.
🔹 throw is used inside the method to actually throw an exception.

Example:


public void processPayment(double amount) throws IllegalArgumentException { if (amount <= 0) { throw new IllegalArgumentException("Amount must be greater than zero"); } System.out.println("Processing payment: " + amount); }

💡 Trick: Many candidates confuse throw and throws, but remember that throw actually throws the exception, while throws just declares it.


2️⃣ Can a method declare throws but never actually throw an exception?

Answer: Yes, a method can declare throws even if it does not explicitly throw an exception inside.

Example:


public void dummyMethod() throws IOException { // No actual exception thrown inside System.out.println("This method declares IOException but does not throw it."); }

💡 Trick: Some interviewers use this question to check if you understand that throws is just a declaration and does not enforce throwing an exception inside the method.


3️⃣ What happens if we write throw without specifying an exception?

Answer: The code will not compile.

🔹 The throw statement must be followed by an exception object.
🔹 Java requires an explicit exception object (of type Throwable or its subclasses).

Incorrect Code:


public void testMethod() { throw; // Compilation error: 'throw' must be followed by an exception instance }

Correct Code:


public void testMethod() { throw new RuntimeException("Something went wrong!"); }

💡 Trick: Java does not allow a bare throw statement without an exception object.


4️⃣ Can we throw multiple exceptions using throw?

Answer: No, throw can only throw one exception at a time.

🔹 If multiple exceptions need to be thrown, they must be handled in separate conditions or wrapped in a combined exception.

Incorrect Code:


throw new IOException(); throw new SQLException(); // Compilation error: unreachable code

Correct Code:


public void checkErrors(boolean condition1, boolean condition2) { if (condition1) { throw new IOException("File error"); } else if (condition2) { throw new SQLException("Database error"); } }

💡 Trick: Unlike throws, which can declare multiple exceptions, throw can only send one exception at a time.


5️⃣ What happens if we declare a throws clause in main()?

Answer: The main() method can declare throws, and any unhandled exception will be propagated to the JVM.

Example:


public static void main(String[] args) throws IOException { readFile("nonexistent.txt"); // Exception not handled, JVM will terminate the program if it occurs } public static void readFile(String filePath) throws IOException { FileReader fr = new FileReader(filePath); // May throw IOException }

💡 Trick: If main() has throws Exception, the program may crash unless handled properly using try-catch.


6️⃣ Why should we prefer custom exceptions over generic exceptions in throw?

Answer: Custom exceptions provide better clarity and help in debugging issues more effectively.

🔹 Instead of throwing a generic exception like Exception or RuntimeException, we should create our own meaningful exceptions.

Example:


class InsufficientBalanceException extends Exception { public InsufficientBalanceException(String message) { super(message); } } public void withdraw(double amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException("Balance is too low!"); } balance -= amount; }

💡 Trick: A well-defined exception name (like InsufficientBalanceException) makes debugging much easier than throw new RuntimeException("Something went wrong").


7️⃣ What happens if we throw an exception inside a finally block?

Answer: If an exception is thrown inside the finally block, it overrides any previous exceptions thrown in try or catch.

Example:


public void testMethod() { try { throw new IOException("Try block exception"); } catch (Exception e) { System.out.println("Caught: " + e.getMessage()); } finally { throw new RuntimeException("Finally block exception"); // Overrides previous exception } }

Output:


Exception in thread "main" java.lang.RuntimeException: Finally block exception

💡 Trick: Any exception in finally will suppress exceptions from try and catch, so avoid throwing exceptions from finally unless necessary.


8️⃣ What happens if a checked exception is thrown but not declared using throws or handled using try-catch?

Answer: The code will not compile because Java enforces checked exceptions to be either:

  1. Handled using try-catch

  2. Declared using throws

Incorrect Code (Compilation Error):


public void readFile() { FileReader fr = new FileReader("file.txt"); // Compilation error: Unhandled exception }

Correct Code:


public void readFile() throws IOException { FileReader fr = new FileReader("file.txt"); // No compilation error now }

💡 Trick: Java forces you to handle checked exceptions, unlike unchecked exceptions.


9️⃣ Can we override a method and remove throws from the overridden method?

Answer: Yes, a subclass can remove the throws clause while overriding a method, but it cannot declare new broader exceptions than the superclass.

Example:


class Parent { public void display() throws IOException { System.out.println("Parent method"); } } class Child extends Parent { @Override public void display() { // Removed 'throws IOException' System.out.println("Child method"); } }

💡 Trick: A subclass can handle exceptions internally and remove throws, but it cannot declare new broader exceptions (e.g., Exception instead of IOException).


🔟 Can we use throws with finally?

Answer: Yes, but the finally block executes before the method exits, even if an exception is thrown.

Example:


public void riskyMethod() throws IOException { try { throw new IOException("Try block exception"); } finally { System.out.println("Finally block executed"); } }

💡 Trick: finally will always execute before the exception propagates to the caller.


🔥 Quick Recap (for Interviews)

throwActually throws an exception.
throwsDeclares that a method may throw an exception.
throw requires an exception object.
throws does not require an object—just a declaration.
✅ A method can throws multiple exceptions but can only throw one at a time.
✅ Exceptions in finally override exceptions from try-catch.

No comments:

Post a Comment