code
EXCEPTIONS IN JAVA
Definition & Hierarchy
Throwable
Error Exception
(Unchecked)
RuntimeException Checked
(Unchecked) Exceptions
Core Java Programming | Topic: Exception Hierarchy | Duration: 20 minutes
Intermediate Level
WHAT YOU'LL LEARN
By the end of this session:
Understand What Exceptions Are Master the Exception Hierarchy
check_circle check_circle
Events that disrupt normal program flow Throwable → Error → Exception
Why we need them (clean error handling) Checked vs Unchecked exceptions
Identify Common Exceptions Know the Key Rules
check_circle check_circle
RuntimeException family What must be handled vs optional
Checked exceptions (IOException, etc.) When to use which type
lightbulb Pro Tip: Exceptions are NOT errors - they're events that need attention!
REAL-WORLD ANALOGY: DRIVING
EXCEPTIONAL SITUATIONS
Check Engine Light → CHECKED EXCEPTION
warning • You MUST check it before long trip
NORMAL FLOW • Compiler forces you to handle
• Example: FileNotFoundException
Start arrow_forward Drive arrow_forward Arrive
Flat Tire → UNCHECKED EXCEPTION
error_outline • Happens unexpectedly during drive
• You CAN handle it if you want
lightbulb KEY INSIGHT • Example: NullPointerException
Different problems need different responses!
Engine Fire → ERROR
local_fire_department • Catastrophic failure
• You CAN'T really handle it
• Example: OutOfMemoryError
WHAT IS AN EXCEPTION?
close WITHOUT EXCEPTIONS (Old way)
public int divide(int a, int b) {
if(b == 0) return -1; // Error code
return a / b;
}
// Problem: -1 might be valid result!
info DEFINITION
An exception is an event that occurs during check_circle WITH EXCEPTIONS (Java way)
program execution that disrupts the normal
public int divide(int a, int b) {
flow of instructions. if(b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
check Clean separation check Rich error info check Cannot be ignored
THE EXCEPTION HIERARCHY
[Link]
arrow_downward
Throwable CATEGORY COMPARISON
(The root of all) Category Description Handling
Error Exception Error JVM/system problems NOT required
(Serious problems) (Recoverable)
Checked Predictable issues MUST handle
OutOfMemoryError
RuntimeException Checked
arrow_downward StackOverflowError (Unchecked) Exceptions Runtime Programming mistakes Optional
arrow_downward NullPointerException IOException
ArithmeticException SQLException
ArrayIndexOutOfBounds
THROWABLE - THE ROOT CLASS
functions KEY METHODS
• String getMessage() Returns detailed message about the exception
account_tree SUPERCLASS
• void printStackTrace() Prints where exception occurred
[Link] is the superclass of all
errors and exceptions in Java.
• String toString() Returns short description
Only Throwable objects can be: code EXAMPLE
try {
arrow_right thrown (throw new Exception())
int x = 10 / 0;
arrow_right caught (catch(Exception e)) } catch(ArithmeticException e) {
[Link]([Link]()); // "/ by zero"
[Link](); // Shows line number
}
ERROR CLASS - DON'T CATCH!
list_alt COMMON ERRORS
1. OutOfMemoryError
error DEFINITION • JVM runs out of memory
Errors indicate serious problems that a normal • Example: creating too many objects
application should NOT try to catch.
2. StackOverflowError
warning RULE: NEVER Catch Errors!
• Stack memory exhausted
• Example: infinite recursion void method() { method(); }
close Can't recover from them
close May leave JVM unstable
close Let the program terminate
3. NoClassDefFoundError
• Class not found at runtime
• Missing JAR file
EXCEPTION CLASS - TWO BRANCHES
COMPARISON TABLE
Exception
RuntimeException Checked
Aspect
(Unchecked) Exceptions
arrow_downward arrow_downward Checked at RUN TIME COMPILE TIME
RuntimeException Checked
Handling OPTIONAL MANDATORY
(Unchecked) Exceptions
Cause Programming bug External factors
Programming mistakes External issues
(bugs in code) (file missing, network NullPointer, IOException,
down) Examples Arithmetic, SQLException,
ArrayIndexOutOfBounds ClassNotFound
CHECKED EXCEPTIONS - MUST HANDLE
code COMPILER ENFORCEMENT
close COMPILE ERROR!
assignment_turned_in DEFINITION
FileReader fr = new FileReader("[Link]");
Exceptions checked at COMPILE TIME.
Compiler FORCES you to handle them.
check_circle Fix 1: Handle with try-catch check_circle Fix 2: Declare with throws
COMMON CHECKED EXCEPTIONS try { void readFile() throws
FileReader fr = new IOException {
• IOException - File/IO operation failed FileReader("[Link]"); FileReader fr = new
} catch(IOException e) { FileReader("[Link]");
• SQLException - Database error
[Link]("File }
• ClassNotFoundException error");
• FileNotFoundException }
• InterruptedException
lightbulb NO CHOICE - either handle OR declare!
UNCHECKED EXCEPTIONS (RUNTIMEEXCEPTION)
warning DEFINITION code COMPILES FINE, CRASHES AT RUNTIME
Exceptions due to PROGRAMMING ERRORS.
check_circle ✓ COMPILES! close ❌ RUNTIME: NullPointerException
NOT checked at compile time - handling optional.
String s = null;
int len = [Link]();
COMMON RUNTIMEEXCEPTIONS
• NullPointerException - Calling method on null check_circle ✓ COMPILES! close ❌ RUNTIME: ArithmeticException
• ArithmeticException - Division by zero
int x = 10 / 0;
• ArrayIndexOutOfBoundsException
• NumberFormatException - Invalid string to number
• IllegalArgumentException
• ClassCastException lightbulb Compiler DOES NOT force you to handle these - but you SHOULD!
CHECKED vs UNCHECKED - QUICK COMPARISON
code CODE EXAMPLES
COMPARISON TABLE
Checked - MUST handle
ASPECT CHECKED UNCHECKED
[Link](1000); // InterruptedException
Checked at COMPILE TIME RUN TIME
Handling MANDATORY OPTIONAL
Unchecked - Optional
Exception
Parent class
(not RuntimeException)
RuntimeException int[] arr = new int[5];
arr[10] = 5; // ArrayIndexOutOfBoundsException
Cause External factors Programming mistakes
IOException, NullPointerException,
Examples
SQLException ArithmeticException check_circle RULE OF THUMB
• Use Checked for recoverable, predictable issues
Analogy Check Engine Light Flat Tire
• Use Unchecked for programming mistakes (bugs)
COMMON EXCEPTIONS - QUICK REFERENCE
report_problem ERRORS
error_outline EXCEPTIONS
EXCEPTION TYPE WHEN IT OCCURS memory OutOfMemoryError
Error
NullPointerException Unchecked Calling method on null object
JVM runs out of memory
ArithmeticException Unchecked Division by zero
ArrayIndexOutOfBounds Unchecked Invalid array index
NumberFormatException Unchecked Parsing invalid string to number
all_inclusive StackOverflowError
Error
IOException Checked File/IO operation failed
Infinite recursion
FileNotFoundException Checked File doesn't exist
SQLException Checked Database error
info KEY INSIGHT
ClassNotFoundException Checked Class not found
Unchecked = Programming bugs
InterruptedException Checked Thread interrupted Checked = External issues
Errors = JVM problems
CREATING CUSTOM EXCEPTIONS
code USAGE EXAMPLE
check_circle 1. Custom Checked Exception class BankAccount {
void withdraw(double amount)
class InsufficientFundsException extends Exception { throws InsufficientFundsException {
public InsufficientFundsException(String msg) { if(amount > balance) {
super(msg); throw new InsufficientFundsException(
} "Insufficient balance");
} }
}
void setAge(int age) {
if(age < 0 || age > 150) {
warning 2. Custom Unchecked Exception throw new InvalidAgeException(
"Invalid age: " + age);
}
class InvalidAgeException extends RuntimeException {
}
public InvalidAgeException(String msg) {
}
super(msg);
}
}
lightbulb Choose checked for recoverable business rules, unchecked for
programming errors
KEY TAKEAWAYS
compare_arrows CHECKED vs UNCHECKED
✓ CHECKED:
account_tree HIERARCHY RULES • Must handle (try-catch) or declare (throws)
stars BEST PRACTICES
• Catch specific exceptions, not generic
check_circle Throwable is the root of ALL • Compiler enforces this
Examples: IOException, SQLException
• Don't ignore exceptions (empty catch)
cancel Error = JVM problems - DON'T catch
• Use custom exceptions for business logic
check_circle Exception = Application problems - DO ✓ UNCHECKED (RuntimeException):
catch • Never catch Errors
• Handling optional
• Indicates programming bug
Examples: NullPointerException
format_quote "Exceptions are your friends - they tell you what went wrong and where!"
QUICK QUIZ & SUMMARY
quiz TEST YOUR KNOWLEDGE
Q1: What is the root class of all exceptions? account_tree SUMMARY HIERARCHY
a) Exception check b) Throwable
Throwable
c) Error d) Object
Q2: Which type MUST be handled at compile time?
Error Exception
a) Error b) RuntimeException
(Don't catch)
check c) Checked Exception d) All of the above Runtime Checked
(Unchecked) (MUST)
Q3: Is NullPointerException checked or unchecked?
a) Checked check b) Unchecked
Key: Checked = Compiler enforced • Unchecked = Optional •
Q4: Should you catch OutOfMemoryError?
info Error = Never catch
a) Yes check b) No