Exception
An exception in Java is an unexpected event that occurs during program execution and disrupts the normal flow of the program. Java provides a robust exception handling mechanism to detect, handle, and recover from such runtime problems.
This is a high-frequency interview topic and critical for writing reliable, production-ready Java applications.
What Is an Exception?
- An abnormal condition during execution
- Occurs at runtime
- Causes program termination if not handled
- Represented as an object in Java
int a = 10 / 0; // ArithmeticException
Why Exceptions Occur
Common causes include:
- Invalid input
- Divide by zero
- Accessing invalid array index
- Null object access
- File or network issues
Exception vs Error (Important Distinction)
| Aspect | Exception | Error |
|---|---|---|
| Nature | Recoverable | Non-recoverable |
| Occurs due to | Program logic / runtime issues | JVM or system failure |
| Handling | Can be handled | Should not be handled |
| Example | NullPointerException | OutOfMemoryError |
Exception Hierarchy (Interview Favorite)
Throwable
├── Exception
│ ├── Checked Exceptions
│ │ └── IOException
│ └── Unchecked Exceptions
│ └── RuntimeException
│ ├── NullPointerException
│ ├── ArithmeticException
│ └── ArrayIndexOutOfBoundsException
└── Error
Types of Exceptions in Java
1️⃣ Checked Exceptions (Compile-Time)
- Checked at compile time
- Must be handled or declared
- Usually external or recoverable issues
FileReader fr = new FileReader("file.txt"); // IOException
Examples:
- IOException
- SQLException
- ClassNotFoundException
2️⃣ Unchecked Exceptions (Runtime)
- Occur at runtime
- Not checked by compiler
- Usually programming mistakes
int[] arr = new int[3];
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
Examples:
- NullPointerException
- ArithmeticException
- NumberFormatException
3️⃣ Errors
- Serious JVM/system problems
- Not meant to be handled
Examples:
- OutOfMemoryError
- StackOverflowError
What Happens When an Exception Occurs
- Exception object is created
- JVM looks for handling code
- If found → exception handled
- If not found → program terminates abnormally
Why Exception Handling Is Important
- Prevents program crash
- Improves reliability
- Enables graceful recovery
- Helps debugging
- Mandatory for real-world applications
Exception Handling Keywords (Preview)
Java provides five keywords:
- try
- catch
- finally
- throw
- throws
(Handled in next topics)
Exception vs Bug vs Error
| Term | Meaning |
|---|---|
| Bug | Coding mistake |
| Exception | Runtime abnormal event |
| Error | JVM/system failure |
Common Beginner Misconceptions
- Thinking all exceptions are errors
- Ignoring unchecked exceptions
- Catching generic Exception everywhere
- Assuming exceptions occur only in bad code
Interview-Ready Answers
Short Answer
An exception is an abnormal event that occurs during program execution and disrupts normal flow.
Detailed Answer
In Java, an exception is an object that represents an error condition occurring at runtime. Java provides an exception handling mechanism using try-catch blocks to handle such events gracefully and prevent program termination.
Exception Handling Examples (Quick Reference)
1. Basic try-catch
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Division by zero");
}
}
}
Output
Division by zero
2. Exception Without Handling (Program Crash)
class Demo {
public static void main(String[] args) {
int a = 10 / 0;
System.out.println("End");
}
}
Explanation
- Unhandled exception
- Program terminates abnormally
3. Multiple catch Blocks
class Demo {
public static void main(String[] args) {
try {
String s = null;
System.out.println(s.length());
} catch (ArithmeticException e) {
System.out.println("Math error");
} catch (NullPointerException e) {
System.out.println("Null error");
}
}
}
Output
Null error
4. Catch Order Matters (Most Specific First)
class Demo {
public static void main(String[] args) {
try {
int[] a = new int[2];
a[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array error");
} catch (Exception e) {
System.out.println("Generic error");
}
}
}
Output
Array error
5. Wrong Catch Order (Compile-Time Error)
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
}
// catch (Exception e) {}
// catch (ArithmeticException e) {} // ❌ unreachable
}
}
Explanation
Parent exception must be last.
6. finally Block Always Executes
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println("Catch");
} finally {
System.out.println("Finally");
}
}
}
Output
Catch
Finally
7. finally Without catch
class Demo {
public static void main(String[] args) {
try {
System.out.println("Try");
} finally {
System.out.println("Finally");
}
}
}
Output
Try
Finally
8. finally Not Executed (System.exit)
class Demo {
public static void main(String[] args) {
try {
System.exit(0);
} finally {
System.out.println("Finally");
}
}
}
Explanation
- JVM terminates immediately
- finally not executed
9. Checked Exception (Compile-Time)
import java.io.FileInputStream;
class Demo {
public static void main(String[] args) {
// FileInputStream f = new FileInputStream("a.txt"); // ❌ compile error
}
}
Explanation
Checked exception must be handled or declared.
10. Handling Checked Exception with throws
import java.io.FileInputStream;
import java.io.FileNotFoundException;
class Demo {
static void read() throws FileNotFoundException {
new FileInputStream("a.txt");
}
public static void main(String[] args) throws FileNotFoundException {
read();
}
}
11. Handling Checked Exception with try-catch
import java.io.FileInputStream;
class Demo {
public static void main(String[] args) {
try {
new FileInputStream("a.txt");
} catch (Exception e) {
System.out.println("File not found");
}
}
}
Output
File not found
12. Unchecked Exception Example
class Demo {
public static void main(String[] args) {
int[] a = new int[2];
a[5] = 10;
}
}
Explanation
- Unchecked exception
- No compile-time checking
13. Exception Propagation
class Demo {
static void m1() {
m2();
}
static void m2() {
int a = 10 / 0;
}
public static void main(String[] args) {
try {
m1();
} catch (Exception e) {
System.out.println("Handled in main");
}
}
}
Output
Handled in main
14. throw Keyword
class Demo {
static void check(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible");
}
System.out.println("Eligible");
}
public static void main(String[] args) {
check(15);
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: Not eligible
15. Custom Exception (User-Defined)
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}
class Demo {
static void check(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Under age");
}
}
public static void main(String[] args) throws InvalidAgeException {
check(16);
}
}
16. Custom Exception Handling
class InvalidAmountException extends RuntimeException {
InvalidAmountException(String msg) {
super(msg);
}
}
class Demo {
static void pay(int amount) {
if (amount <= 0) {
throw new InvalidAmountException("Invalid amount");
}
System.out.println("Paid");
}
public static void main(String[] args) {
try {
pay(-10);
} catch (InvalidAmountException e) {
System.out.println(e.getMessage());
}
}
}
Output
Invalid amount
17. return in try vs finally
class Demo {
static int test() {
try {
return 10;
} finally {
return 20;
}
}
public static void main(String[] args) {
System.out.println(test());
}
}
Output
20
18. Exception with catch (Exception e)
class Demo {
public static void main(String[] args) {
try {
String s = null;
System.out.println(s.length());
} catch (Exception e) {
System.out.println("Handled");
}
}
}
Output
Handled
19. Multiple Exceptions in Single Catch (Java 7+)
class Demo {
public static void main(String[] args) {
try {
int[] a = new int[2];
a[5] = 10;
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("Array or Null error");
}
}
}
Output
Array or Null error
20. Interview Summary – Exception Handling
class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception handled");
}
System.out.println("Program continues");
}
}
Key Points
- Prevents abnormal termination
- Separates error handling from logic
- Supports recovery & graceful flow
Output
Exception handled
Program continues
Key Takeaway
Exceptions are runtime problems, not system failures. Proper exception handling ensures robust, stable, and maintainable Java applications.