1. The Hook (The "Byte-Sized" Intro)
In a Nutshell: Java provides many built-in exceptions for common error scenarios: NullPointerException (null reference), ArrayIndexOutOfBoundsException (invalid index), ArithmeticException (math errors), NumberFormatException (parsing errors), etc. Knowing when each occurs helps you write defensive code and handle errors appropriately.
Think of car dashboard lights. Each light (exception) indicates a specific problem: oil low, tire pressure, engine temperature. Same with Java exceptions—specific errors, specific solutions!
2. Conceptual Clarity (The "Simple" Tier)
💡 The Analogy: The Medical Symptoms
- NullPointerException: Missing organ (critical!)
- ArrayIndexOutOfBounds: Took too many pills
- ArithmeticException: Divided prescription by zero doses
- NumberFormatException: Can't read doctor's handwriting
Each symptom → specific diagnosis → specific treatment!
3. Technical Mastery (The "Deep Dive")
Common Exceptions Catalog
| Exception | Cause | Prevention |
|---|---|---|
NullPointerException | Accessing null reference | Null checks, Optional |
ArrayIndexOutOfBoundsException | Invalid array index | Bounds checking |
ArithmeticException | Division by zero | Validate divisor |
NumberFormatException | Invalid string-to-number | Validate before parsing |
ClassCastException | Invalid type cast | instanceof check |
IllegalArgumentException | Invalid method argument | Validation |
IOException | I/O operation failed | try-catch, exists() |
FileNotFoundException | File doesn't exist | File.exists() check |
4. Interactive & Applied Code
public class CommonExceptionsDemo {
public static void main(String[] args) {
// 1. NullPointerException
nullPointerExample();
// 2. ArrayIndexOutOfBoundsException
arrayIndexExample();
// 3. ArithmeticException
arithmeticExample();
// 4. NumberFormatException
numberFormatExample();
// 5. ClassCastException
classCastExample();
// 6. IllegalArgumentException
illegalArgumentExample();
}
static void nullPointerExample() {
String str = null;
try {
System.out.println(str.length()); // ❌ NullPointerException
} catch (NullPointerException e) {
System.out.println("❌ Null reference: " + e.getMessage());
}
// ✅ Prevention
if (str != null) {
System.out.println(str.length());
}
}
static void arrayIndexExample() {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[10]); // ❌ ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("❌ Invalid index: " + e.getMessage());
}
// ✅ Prevention
int index = 10;
if (index >= 0 && index < arr.length) {
System.out.println(arr[index]);
}
}
static void arithmeticExample() {
try {
int result = 10 / 0; // ❌ ArithmeticException
} catch (ArithmeticException e) {
System.out.println("❌ Division by zero");
}
// ✅ Prevention
int divisor = 0;
if (divisor != 0) {
int result = 10 / divisor;
}
}
static void numberFormatExample() {
try {
int num = Integer.parseInt("abc"); // ❌ NumberFormatException
} catch (NumberFormatException e) {
System.out.println("❌ Invalid number format");
}
// ✅ Prevention (validate or use try-catch)
String input = "123";
if (input.matches("\\d+")) {
int num = Integer.parseInt(input);
}
}
static void classCastExample() {
Object obj = "Hello";
try {
Integer num = (Integer) obj; // ❌ ClassCastException
} catch (ClassCastException e) {
System.out.println("❌ Invalid cast");
}
// ✅ Prevention
if (obj instanceof Integer) {
Integer num = (Integer) obj;
}
}
static void illegalArgumentExample() {
try {
setAge(-5); // ❌ IllegalArgumentException
} catch (IllegalArgumentException e) {
System.out.println("❌ " + e.getMessage());
}
}
static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}5. The Comparison & Decision Layer
Decision Tree: Which Exception to Throw?
6. The "Interview Corner" (The Edge)
The "Killer" Interview Question: "What's the difference between IllegalArgumentException and IllegalStateException?" Answer:
- IllegalArgumentException: Input/parameter is invalid (bad argument passed)
- IllegalStateException: Object state is invalid (operation not allowed now)
void withdraw(int amount) {
if (amount < 0) throw new IllegalArgumentException("Negative amount");
if (accountClosed) throw new IllegalStateException("Account closed");
}Pro-Tip: Use Objects.requireNonNull() (Java 7+) for null checks:
public void setName(String name) {
this.name = Objects.requireNonNull(name, "Name cannot be null");
}Cleaner than manual null checks!