Lesson Completion
Back to course

Common Built-in Exceptions: The Standard Error Catalog

Intermediate
15 minutes4.8Java

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

ExceptionCausePrevention
NullPointerExceptionAccessing null referenceNull checks, Optional
ArrayIndexOutOfBoundsExceptionInvalid array indexBounds checking
ArithmeticExceptionDivision by zeroValidate divisor
NumberFormatExceptionInvalid string-to-numberValidate before parsing
ClassCastExceptionInvalid type castinstanceof check
IllegalArgumentExceptionInvalid method argumentValidation
IOExceptionI/O operation failedtry-catch, exists()
FileNotFoundExceptionFile doesn't existFile.exists() check

4. Interactive & Applied Code

java
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?

graph TD A{What's wrong?} A -- Null reference --> B[NullPointerException] A -- Invalid argument --> C[IllegalArgumentException] A -- Invalid state --> D[IllegalStateException] A -- Math error --> E[ArithmeticException] A -- I/O error --> F[IOException]

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)
java
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:

java
public void setName(String name) { this.name = Objects.requireNonNull(name, "Name cannot be null"); }

Cleaner than manual null checks!

Topics Covered

Java FundamentalsError Handling

Tags

#java#exceptions#try-catch#error-handling#robust-code

Last Updated

2025-02-01