← Back to Home

Exception Scenarios

Below are real-world and interview-grade exception scenarios that test understanding of exception flow, hierarchy, propagation, and best practices. Each scenario explains what happens and why.

1️⃣ Arithmetic Exception

Scenario

int a = 10 / 0;
          

Exception

ArithmeticException

Why

Division by zero for integer arithmetic is undefined.

Interview Note

  • ✔ Unchecked exception
  • ✔ Occurs at runtime

2️⃣ NullPointerException (Most Common)

Scenario

String s = null;
System.out.println(s.length());
          

Exception

NullPointerException

Why

Calling a method on a null reference.

Best Practice

Use Optional, null checks, or proper initialization.

3️⃣ ArrayIndexOutOfBoundsException

Scenario

int[] arr = {1, 2, 3};
System.out.println(arr[5]);
          

Exception

ArrayIndexOutOfBoundsException

Why

Index outside valid range (0 to length-1).

4️⃣ StringIndexOutOfBoundsException

Scenario

String s = "Java";
System.out.println(s.charAt(10));
          

Exception

StringIndexOutOfBoundsException

Why

Invalid character index.

5️⃣ NumberFormatException

Scenario

int x = Integer.parseInt("abc");
          

Exception

NumberFormatException

Why

Invalid string format for numeric conversion.

6️⃣ ClassCastException

Scenario

Object o = "Java";
Integer i = (Integer) o;
          

Exception

ClassCastException

Why

Incompatible object type casting.

Interview Tip

  • ✔ Happens at runtime
  • ✔ Use instanceof to avoid

7️⃣ FileNotFoundException (Checked)

Scenario

FileInputStream fis = new FileInputStream("data.txt");
          

Exception

FileNotFoundException

Why

File does not exist at the specified path.

Interview Note

  • ✔ Checked exception
  • ✔ Must be handled or declared

8️⃣ IOException During File Operations

Scenario

BufferedReader br = new BufferedReader(new FileReader("a.txt"));
br.readLine();
          

Exception

IOException

Why

I/O failure during read/write operations.

9️⃣ SQLException (Database Scenario)

Scenario

Connection con = DriverManager.getConnection(url, user, pass);
          

Exception

SQLException

Why

DB connectivity issues, wrong credentials, network problems.

🔟 InterruptedException (Multithreading)

Scenario

Thread.sleep(1000);
          

Exception

InterruptedException

Why

Thread interrupted while sleeping or waiting.

Best Practice

✔ Restore interrupt status or handle gracefully

1️⃣1️⃣ StackOverflowError (Error, not Exception)

Scenario

void test() {
    test();
}
          

Error

StackOverflowError

Why

Infinite recursion consumes stack memory.

1️⃣2️⃣ OutOfMemoryError

Scenario

List list = new ArrayList<>();
while (true) {
    list.add(new int[1000000]);
}
          

Error

OutOfMemoryError

Why

Heap memory exhausted.

1️⃣3️⃣ Exception in finally Block

Scenario

try {
    int a = 10 / 0;
} finally {
    int b = 10 / 0;
}
          

Outcome

  • Original exception lost
  • Exception from finally propagates

Interview Trap

❗ Avoid throwing exceptions from finally

1️⃣4️⃣ Return Statement in finally

Scenario

try {
    return 10;
} finally {
    return 20;
}
          

Output

20

Why

finally overrides return from try

1️⃣5️⃣ Multiple catch Order (Inheritance Rule)

Scenario

try {
    // code
} catch (Exception e) {
} catch (ArithmeticException e) { // ❌ compile-time error
}
          

Why

Child exception must come before parent.

1️⃣6️⃣ Unhandled Checked Exception

Scenario

FileInputStream fis = new FileInputStream("a.txt");
          

Error

Compilation error

Why

Checked exception not handled or declared.

1️⃣7️⃣ throw vs throws Scenario

throw

throw new ArithmeticException("Error");
          

✔ Explicitly throws an exception

throws

void read() throws IOException {}
          

✔ Declares exception responsibility

1️⃣8️⃣ Custom Exception Scenario

Scenario

if (age < 18) {
    throw new InvalidAgeException();
}
          

✔ Used for business rules

1️⃣9️⃣ Exception Propagation

Scenario

void m1() {
    m2();
}
void m2() {
    int a = 10 / 0;
}
          

Behavior

Exception propagates up the call stack until handled.

2️⃣0️⃣ try-with-resources Scenario (Best Practice)

try (FileInputStream fis = new FileInputStream("a.txt")) {
    // use file
}
          
  • ✔ Resource closed automatically
  • ✔ No finally needed

Interview-Ready Summary Table

Scenario Type Result
Runtime error Unchecked exception
Compile-time error Checked exception
finally block Executes always (mostly)
Checked exception Must handle or declare
Error JVM-level issue

Ultra-Short Interview Answer

Exception scenarios demonstrate how Java handles runtime and checked failures such as null access, arithmetic errors, I/O failures, and resource handling using try-catch-finally and exception propagation.

Key Takeaway

Good Java developers don’t just catch exceptions — they understand when, why, and how they occur.