KTU OOP Java2024 Scheme • 60M ESE
MODULE 3/Section 3: Exception Handling

Errors vs Exceptions, Exception Hierarchy, Checked vs Unchecked & Default Handler

HIGH PRIORITY (Prep Guide)Official Syllabus~16 min study
Official KTU 2024 Syllabus Topics Covered Here
Introduction to errors and exceptionsException hierarchyChecked exceptionsUnchecked exceptions

1. Topic Introduction

Even cleanly compiled Java programs face unexpected runtime troubles—dividing by zero, reading a missing file, accessing an invalid array slot, or losing a database connection. Without Exception Handling, the JVM abruptly crashes the entire application. Understanding Java's Throwable class hierarchy and the vital distinction between Checked and Unchecked exceptions is top-priority exam territory.

2. Start From Zero: Airplane Turbulence (Exception) vs Engine Falling Off (Error)

During a flight, bad weather (IOException = Checked Exception) is predictable—aviation rules force pilots at takeoff (compile time) to file an emergency landing plan (try-catch or throws). Pilot miscalculations (ArithmeticException = Unchecked RuntimeException) happen mid-air due to logic bugs—the compiler doesn't force checks, you should simply fly better! Meanwhile, a wing snapping off (StackOverflowError / OutOfMemoryError = Error) is a catastrophic hardware/JVM failure that user code isn't expected to fix mid-flight.

Key Takeaway: All errors & exceptions descend from java.lang.Throwable: Error (severe JVM failure, unchecked) and Exception, which splits into Checked Exceptions (enforced at compile time) and **RuntimeException (Unchecked)**.

3. Essential Exam Definitions

Exception
An abnormal event/condition arising during program execution (runtime) that disrupts normal sequential instruction flow, represented in Java as an object descending from java.lang.Throwable.
Checked Exception
An Exception subclass (EXCLUDING RuntimeException and Error) checked strictly by javac at compile time; the programmer MUST handle it with try-catch or declare it via throws (IOException, SQLException, ClassNotFoundException).
Unchecked Exception
An exception descending from RuntimeException (or Error) that is NOT checked by javac at compile time, typically caused by programmer logic mistakes (ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException).
JVM Default Exception Handler
Built-in runtime fallback triggered when an exception is never caught by user code; prints the exception name/message, prints a call stack trace, and terminates the thread.

4. Detailed Technical Explanation & Syntax

1. Compile-Time Errors vs Runtime Errors vs Exceptions

Compile-time errors (syntax errors like missing semicolons or type mismatches) are caught by javac before .class is even produced. Runtime errors occur while running .class on the JVM—Java turns recoverable runtime conditions into Exception objects so your code can catch and recover cleanly.

2. The Throwable Class Hierarchy

All exception types subclass java.lang.Throwable (which itself extends Object). Throwable splits into two main branches:

  • Branch 1 — Error: Serious JVM environment failures (StackOverflowError, OutOfMemoryError, VirtualMachineError). Programs normally do NOT catch these.
  • Branch 2 — Exception: Exceptional conditions user programs should catch or declare. Splits into:
  • -> Checked Exceptions (Exception subclasses excluding RuntimeException): IOException, FileNotFoundException, SQLException, ClassNotFoundException, InterruptedException.
  • -> Unchecked Exceptions (RuntimeException subclasses): ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, IllegalArgumentException.

3. Five Exception-Handling Keywords & Uncaught Exceptions

Java manages exception handling using five reserved keywords: **try, catch, throw, throws, and finally**.

If a method divides by zero (10 / 0) without a try-catch, the JVM creates an ArithmeticException object, stops executing further statements in main(), hands it to the Default Handler, prints Exception in thread "main" java.lang.ArithmeticException: / by zero + stack trace, and terminates the program.

5. Working Principle: Compiler Rule: Checked vs Unchecked Verification

  1. When javac compiles a call like FileReader f = new FileReader("data.txt");, it sees FileNotFoundException (Checked).
  2. If neither try-catch nor throws FileNotFoundException wraps it, compilation FAILS immediately (unreported exception).
  3. When javac compiles int x = 10 / 0;, ArithmeticException is a RuntimeException (Unchecked), so compilation SUCCEEDS—failure occurs at runtime if unhandled.

6. Examination-Ready Diagrams

Diagram 9

Java Exception Class Hierarchy

java.lang.Objectjava.lang.ThrowableRoot of all errors & exceptionsExceptionProgram-recoverable conditionsError (Unchecked)JVM failure: StackOverflowError, OutOfMemoryErrorChecked ExceptionsIOException, SQLException, FileNotFound, ClassNotFoundRuntimeException (Unchecked)ArithmeticException, NullPointer, ArrayIndexOutOfBounds

Complete java.lang.Throwable class tree partitioning runtime issues into Error (unchecked JVM failures) and Exception (Checked vs RuntimeException Unchecked).

Key Components
  • Object -> Throwable: Root superclass of all errors and exceptions; only Throwable subclasses can be thrown/caught.
  • Error (Unchecked): Severe JVM/environment failures like StackOverflowError, OutOfMemoryError (not caught normally).
  • Exception (Checked): Compile-time verified exceptions like IOException, SQLException, ClassNotFoundException.
  • RuntimeException (Unchecked): Logic/programming bugs checked only at runtime: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException.
Step-by-Step Flow
  1. java.lang.Object is parent of java.lang.Throwable.
  2. Throwable splits into two main branches: Error and Exception.
  3. Under Exception, RuntimeException (and its subclasses) are Unchecked; all other Exception subclasses are Checked.
How to Draw in KTU Exam
  • Always start from Object -> Throwable at the top.
  • Split cleanly into two branches: Exception (left) and Error (right).
  • Under Exception, clearly draw two sub-groups: Checked Exceptions (IOException, SQLException, FileNotFoundException, ClassNotFoundException) and RuntimeException (Unchecked) (ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException).

7. Complete Java Code Examples & Tracing

Handling Unchecked Exception & Seeing Checked Exception EnforcementCheckedVsUncheckedDemo.java
Shows recovery from ArithmeticException (unchecked) and required handling for ClassNotFoundException (checked).
1public class CheckedVsUncheckedDemo {
2 public static void main(String[] args) {
3 // 1. Unchecked Exception (RuntimeException): compiler does not force try-catch
4 try {
5 int a = 10, b = 0;
6 int c = a / b; // Throws ArithmeticException here!
7 System.out.println("This line never executes: " + c);
8 } catch (ArithmeticException e) {
9 System.out.println("Caught Unchecked Exception: " + e.toString());
10 }
11
12 // 2. Checked Exception: MUST be caught or declared with 'throws'
13 try {
14 Class.forName("com.missing.FakeDriver");
15 } catch (ClassNotFoundException e) {
16 System.out.println("Caught Checked Exception: " + e.getMessage());
17 }
18
19 System.out.println("Program recovered and finished gracefully!");
20 }
21}
Expected Output
Caught Unchecked Exception: java.lang.ArithmeticException: / by zero
Caught Checked Exception: com.missing.FakeDriver
Program recovered and finished gracefully!
Keywords:ThrowableExceptionRuntimeExceptionErrortrycatch
Common Exam & Coding Mistakes
  • Thinking RuntimeException is a Checked exception (it is the root of UNCHECKED exceptions!).
  • Thinking Error can/should be caught routinely with catch (Throwable t).

Comparison Tables

Checked Exceptions vs Unchecked Exceptions (Must-Know Table)
CriterionChecked ExceptionsUnchecked Exceptions
Checking TimeChecked at COMPILE TIME by javacChecked at RUNTIME by JVM
Base ClassException (excluding RuntimeException)RuntimeException (and Error)
Handling RequirementMandatory (try-catch or throws)Optional (not enforced by compiler)
Typical CauseExternal failures (missing file, broken DB/network)Programming bugs (null dereference, /0, bad index)
Common ExamplesIOException, FileNotFoundException, SQLException, ClassNotFoundException, InterruptedExceptionArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException

Real-World Applications

  • File parsers catch IOException/FileNotFoundException to prompt users politely instead of crashing.
  • Network/JDBC calls handle SQLException to roll back database transactions safely.

Important KTU Exam Points

  • Always draw Diagram 9 starting at Object -> Throwable -> Exception & Error -> Checked vs RuntimeException (Unchecked)!
  • List at least 4 Checked and 4 Unchecked exception class names accurately.

Memory Techniques & Revision

  • 5 Exception Keywords — 'T-C-T-T-F': try, catch, throw, throws, finally.
  • Checked = 'External I/O/DB/Class' (IO, SQL, ClassNotFound, Interrupted); Unchecked = 'Logic Bugs' (Arithmetic, NullPointer, ArrayIndex).

Common Pitfalls to Avoid

  • Forgetting that Error (e.g. StackOverflowError) also falls under unchecked throwables.

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: An exception is an abnormal runtime condition represented by an object descending from java.lang.Throwable. Java categorizes runtime problems into Checked Exceptions, Unchecked Exceptions, and Errors.

  • Hierarchy: Object -> Throwable, splitting into Error (JVM/environment failures like StackOverflowError) and Exception.
  • Checked Exceptions: Subclasses of Exception outside RuntimeException (IOException, SQLException, FileNotFoundException, ClassNotFoundException). Verified at compile time; must be handled via try-catch or declared with throws.
  • Unchecked Exceptions: Subclasses of RuntimeException (ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException) plus Error. Not checked at compile time; usually arise from logic errors.
Exam Diagram Note: Reproduce Diagram 9 (Exception Hierarchy Tree) cleanly.

Quick Understanding Check

1. Which of the following is a CHECKED exception in Java?

2. What is the ultimate common superclass of BOTH Error and Exception?