Chapter 6: Exceptions

Object Oriented Programming with Java
What is an exceptiontry and catchMultiple catchfinallytry-with-resourcesNested try Exception hierarchyChecked / uncheckedthrow and throwsCommon exceptionsErrorCustom exceptionsStack trace
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Concept

Define an exception; classify runtime problems as Exception or Error.

Handling

Handle exceptions with try, catch, finally and try-with-resources; trace the flow step by step.

Hierarchy

Explain how Throwable, Error, Exception and RuntimeException relate, and why catch order matters.

Kinds

Tell checked from unchecked exceptions; apply the “catch or declare” rule.

Throwing

Throw exceptions with throw, declare them with throws; trace how an exception propagates up the call stack.

Practice

Recognize common exception classes, write a custom exception class and read a stack trace.

Basics

What Is an Exception?

  • An exception is an unexpected event that occurs while a program runs and disrupts its normal flow.
  • Examples: a file that cannot be found, division by zero, an index outside an array, using a null reference.
  • Exceptions are created automatically by the Java runtime (the JVM) or explicitly by the programmer (throw).
  • In Java an exception is an object: it carries its type, a message and where it happened.
  • The exception mechanism lets you deal with abnormal situations in an orderly way.
When Java hits an exception, it roughly says: “I give up. I don't know what to do now. Somebody else handle this!”
Analogy

A waiter learns in the kitchen that a dish has run out. He can't fix it, so he tells the manager. The manager either solves it (suggests another dish) or passes it further up.

Basics

Runtime Errors: Exception and Error

Compile errors stop a program from running at all; logic errors give no signal. A problem that arises while the program runs is thrown by the JVM as a Throwable object, which has two main branches.

BranchWhat it meansWhat the program can doExample
Exception
(Exception)
An unusual condition the program can anticipateCatch it and recover10 / 0, arr[5] (on a 3-element array), a missing file
Error
(Error)
A serious JVM- or system-level problemUsually not caught; the program endsStackOverflowError, OutOfMemoryError

Exceptions and stack traces are among the most powerful tools for finding and fixing the cause of runtime errors (debugging).

Basics

Uncaught Exception: The Program Crashes

public class Crash {
  public static void main(String[] args) {
    int num = 10, den = 0;
    System.out.println("Start");
    int result = num / den;
    System.out.println("Result: " + result);
    System.out.println("Done");
  }
}
Output
Start
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Crash.main(Crash.java:5)
  • Line 5 divides an integer by zero; the JVM throws an ArithmeticException object.
  • Nobody catches it, so the program terminates: “Result” and “Done” are never printed.
  • The JVM prints the exception's type, message and location (class, method, line).
line 3assignline 4Startline 510 / 0line 6skippedline 7skippedJVM ends the program

Basics

Two Ways to Deal with an Exception

1) Handle it

The method puts the risky code in try and resolves the problem itself in catch.

Example: if the file is missing (FileNotFoundException), a file-reading method shows a message and goes on with default settings.

2) Make it the caller's problem (declare)

The method does not handle the exception; it declares it with throws in its signature. The exception becomes the caller's problem.

The caller faces the same choice: handle it or pass it up.

Which one? The code that can meaningfully resolve the exception should handle it. Code that got the file name from the user can ask again when the file is missing; a low-level read method cannot know that.

Basics

“Something Went Wrong”: With a Return Code

public static int indexOf(String[] names, String name) {
  for (int i = 0; i < names.length; i++) {
    if (names[i].equals(name)) {
      return i;
    }
  }
  return -1;
}
// in main
String[] names = {"Ali", "Ayşe", "Can"};
System.out.println(indexOf(names, "Can"));
int k = indexOf(names, "Ece");   // k = -1
System.out.println(names[k]);
Output
2
java.lang.ArrayIndexOutOfBoundsException:
  Index -1 out of bounds for length 3
  • Exceptions are how a program signals that “something went wrong”.
  • But “wrong” is subjective: is a name that isn't found an error, or a normal result?
  • When there is no match, this method returns -1 instead of throwing an exception.
  • If the caller forgets to check for -1, the error shows up elsewhere, at names[-1] (output on the left).

Basics

Exceptions Instead of Return Codes

public static int find(String[] names, String name) {
  for (int i = 0; i < names.length; i++) {
    if (names[i].equals(name)) {
      return i;
    }
  }
  throw new IllegalArgumentException("Not found: " + name);
}
// in main
try {
  System.out.println(find(names, "Ece"));
} catch (IllegalArgumentException e) {
  System.out.println("Error: " + e.getMessage());
}
Output
Error: Not found: Ece
  • As a rule, avoid special return codes like -1; prefer Java's exception mechanism.
  • Exceptions handle error cases clearly and effectively.

Why exceptions help

  • Clear, consistent error handling; errors never mix with normal results
  • More readable code, easier debugging
  • More reliable code

try and catch

try and catch Statements

try {
  // Code that may fail
  int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
  // Handle the error
  System.out.println("Error: " + e.getMessage());
}
Output
Error: / by zero
trycatchnext codeexceptionno exception
  • The basic structure of error handling.
  • try block: code that may fail.
  • catch block: runs if an exception of the given type occurs inside try, and handles it.
  • catch (ArithmeticException e): e refers to the thrown exception object (like a parameter).
  • If an exception occurs, the rest of try is skipped; if none occurs, catch never runs.
  • After catch, the program continues its normal flow.

try and catch · Step by step

try-catch Flow: Step by Step

println("Before divide")result = num / denprintln("Result: " + …)catch (ArithmeticException e)println("Error: " + …)println("Done")

Variables are created. den is zero: trouble ahead.

println("Before divide")result = num / denprintln("Result: " + …)catch (ArithmeticException e)println("Error: " + …)println("Done")

Normal code outside try runs.

println("Before divide")result = num / denprintln("Result: " + …)catch (ArithmeticException e)println("Error: " + …)println("Done")

We enter the try block; the first line runs fine.

println("Before divide")result = num / denprintln("Result: " + …)catch (ArithmeticException e)println("Error: " + …)println("Done")

10 / 0: the JVM creates an ArithmeticException object and throws it. No assignment happens.

println("Before divide")result = num / denprintln("Result: " + …)catch (ArithmeticException e)✓println("Error: " + …)println("Done")

Type matches: catch runs and e refers to the exception object. The “Result” line was skipped.

println("Before divide")result = num / denprintln("Result: " + …)catch (ArithmeticException e)println("Error: " + …)println("Done")

e.getMessage() → "/ by zero".

println("Before divide")result = num / denprintln("Result: " + …)catch (ArithmeticException e)println("Error: " + …)println("Done")

No crash: after catch, normal flow continues.

public class DivideDemo {
  public static void main(String[] args) {
    int num = 10, den = 0;
    System.out.println("Start");
    try {
      System.out.println("Before divide");
      int result = num / den;
      System.out.println("Result: " + result);
    } catch (ArithmeticException e) {
      System.out.println("Error: " + e.getMessage());
    }
    System.out.println("Done");
  }
}

try and catch

Getting Information from the Exception Object

try {
  int[] arr = new int[3];
  arr[5] = 7;
} catch (ArrayIndexOutOfBoundsException e) {
  System.out.println(e.getMessage());
  System.out.println(e);
  System.out.println(e.getClass().getSimpleName());
  e.printStackTrace();
}
Output
Index 5 out of bounds for length 3
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
ArrayIndexOutOfBoundsException
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    at ExceptionDemo.main(ExceptionDemo.java:5)
MethodReturns
getMessage()Just the message (or null)
toString()Full class name + “: ” + message; println(e) uses it
getClass()The exception's actual class
printStackTrace()toString() + stack trace; writes to System.err
getCause()The exception that caused this one (if any)

try and catch

Multiple catch Blocks

try {
  // Code that may fail
} catch (ArithmeticException e) {
  // Handle ArithmeticException
} catch (NullPointerException e) {
  // Handle NullPointerException
} catch (Exception e) {
  // All other exceptions
}
  • A block of code can throw more than one type of exception.
  • Add a separate catch block per type; each holds the response specific to that type.
  • When an exception is thrown, the catch blocks are tried top to bottom; the first match runs and the rest are skipped.
  • “Match” means the thrown object is the catch type itself or a subclass (the instanceof rule).
  • The final catch (Exception e) is the general case that catches everything else.
NullPointerExceptionthrown objectArithmeticException✗ no match1. catchNullPointerException✓ runs2. catchcatch Exceptionskipped3. catch

try and catch

Chained catch Blocks: Order Matters

✗ General type first

try {
  int result = 10 / 0;
} catch (Exception e) {
  System.out.println("General error");
} catch (ArithmeticException e) {
  System.out.println("Arithmetic error");
}
OrderError.java:7: error: exception ArithmeticException
    has already been caught
  • If the catch types are related by inheritance, order matters: subclasses must come before superclasses.
  • ArithmeticException is an Exception; the first block already catches it, so the second can never run. The compiler rejects this.
  • For unrelated types (ArithmeticException, NullPointerException) order does not matter.

✓ Specific to general

} catch (ArithmeticException e) {
  System.out.println("Arithmetic error");
} catch (Exception e) {
  System.out.println("General error");
}

try and catch · Step by step

Which catch Runs?

NumberFormatException1. catch: NumberFormat2. catch: Arithmetic3. catch: ArrayIndexOutOfBoundsfinally

1st call: parseInt("abc") → NumberFormatException. The division line is skipped.

NumberFormatException1. catch: NumberFormat✓2. catch: Arithmetic3. catch: ArrayIndexOutOfBoundsfinally

The first catch matches and runs; the other catches are not checked.

NumberFormatException1. catch: NumberFormat✓2. catch: Arithmetic3. catch: ArrayIndexOutOfBoundsfinally

Then finally.

ArithmeticException1. catch: NumberFormat2. catch: Arithmetic3. catch: ArrayIndexOutOfBoundsfinally

2nd call: 10 / 0 → ArithmeticException.

ArithmeticException1. catch: NumberFormat✗2. catch: Arithmetic✓3. catch: ArrayIndexOutOfBoundsfinally

The 1st catch doesn't match (✗), the 2nd does (✓).

ArrayIndexOutOfBoundsException1. catch: NumberFormat2. catch: Arithmetic3. catch: ArrayIndexOutOfBoundsfinally

3rd call: the array has one element; input[1] → ArrayIndexOutOfBoundsException.

ArrayIndexOutOfBoundsException1. catch: NumberFormat✗2. catch: Arithmetic✗3. catch: ArrayIndexOutOfBounds✓finally

The first two catches don't match, the third does; then finally.

static void divide(String[] input) {
  try {
    int x = Integer.parseInt(input[0]);
    int y = Integer.parseInt(input[1]);
    System.out.println("Result: " + (x / y));
  } catch (NumberFormatException e) {
    System.out.println("Not a number: " + e.getMessage());
  } catch (ArithmeticException e) {
    System.out.println("Zero: " + e.getMessage());
  } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Missing: " + e.getMessage());
  } finally {
    System.out.println("finally ran");
  }
}
// in main
divide(new String[] {"10", "abc"});
divide(new String[] {"10", "0"});
divide(new String[] {"10"});

try and catch

One catch, Several Types (Java 7+)

try {
  Object o = "Hello";
  Integer i = (Integer) o;
} catch (ClassCastException
    | NullPointerException e) {
  System.out.println("Type or null error: "
    + e.getClass().getSimpleName());
}
Output
Type or null error: ClassCastException
  • Same response? Join the types with | to avoid duplicate code.
  • In this block e is implicitly final; it cannot be reassigned.

✗ Can't combine a subclass with its superclass

} catch (FileNotFoundException
    | IOException e) {
error: Alternatives in a multi-catch statement
  cannot be related by subclassing
  Alternative FileNotFoundException is a
  subclass of alternative IOException
Fix: name only the supertype: catch (IOException e). It already covers the subtype.

finally

The finally Block

try {
  // Code that may fail
} catch (Exception e) {
  // All other exceptions
} finally {
  // Always runs
}
  • Comes after the try and catch blocks.
  • Runs in every case: whether or not an exception occurs, and whether or not it is caught.
  • Even if try or catch contains a return, it runs before the method exits.
  • Guarantees that certain steps run: resource management and cleanup, such as closing files, network and database connections.
  • try must be followed by at least one catch or a finally; try { } finally { } is valid.
  • The one exception: System.exit() stops the JVM at once; finally does not run.

finally · Step by step

finally and return: Step by Step

try { … }catch (ArithmeticException e)finally { … }no return value yet

Before println runs, its argument must be evaluated: divide(10, 2) is called.

try { … }catch (ArithmeticException e)finally { … }no return value yet

The try block starts.

try { … }catch (ArithmeticException e)finally { … }no return value yet

The division succeeds: s = 5.

try { … }catch (ArithmeticException e)finally { … }pending return value: 5

return s: the return value 5 is ready, but the method doesn't end yet…

try { … }catch (ArithmeticException e)finally { … }pending return value: 5

…first finally runs. catch was skipped (no exception).

try { … }catch (ArithmeticException e)finally { … }pending return value: 5

Now 5 is returned and printed.

try { … }catch (ArithmeticException e)finally { … }no return value yet

Second call: divide(10, 0).

try { … }catch (ArithmeticException e)finally { … }no return value yet

try starts.

try { … }catch (ArithmeticException e)finally { … }no return value yet

10 / 0 → exception! The rest of try (“try ended”, return s) is skipped.

try { … }catch (ArithmeticException e)✓finally { … }no return value yet

catch matches and prints the message.

try { … }catch (ArithmeticException e)✓finally { … }pending return value: -1

return -1: the value is ready, but again finally runs first.

try { … }catch (ArithmeticException e)✓finally { … }pending return value: -1

finally runs this time too.

try { … }catch (ArithmeticException e)✓finally { … }pending return value: -1

-1 is returned. So finally ran in both cases.

static int divide(int a, int b) {
  try {
    System.out.println("try started");
    int s = a / b;
    System.out.println("try ended");
    return s;
  } catch (ArithmeticException e) {
    System.out.println("catch: " + e.getMessage());
    return -1;
  } finally {
    System.out.println("finally");
  }
}
public static void main(String[] args) {
  System.out.println("Result = " + divide(10, 2));
  System.out.println("Result = " + divide(10, 0));
}

finally

try-with-resources (Java 7+)

class Resource implements AutoCloseable {
  private String name;
  Resource(String name) {
    this.name = name;
    System.out.println(name + " opened");
  }
  void use(int x) {
    System.out.println(name + " in use");
    int s = 10 / x;
  }
  @Override
  public void close() {
    System.out.println(name + " closed");
  }
}
try (Resource r = new Resource("file")) {
  r.use(0);
} catch (ArithmeticException e) {
  System.out.println("Error: " + e.getMessage());
}
Output
file opened
file in use
file closed
Error: / by zero
  • A resource opened in try (...) is closed automatically (close()) when the block ends, even after an exception.
  • The resource is closed before catch runs. Its class must implement AutoCloseable, as streams, Scanner, NIO channels and database connections do; no finally or null check is needed.
  • This is the modern, safe way to do what finally did for closing resources.

finally · Step by step

Two Resources: Opening and Closing Order

Resource: its constructor prints “… opened”, use prints “… in use”, close() prints “… closed”.

Resources (opening order)fileopennet—

The first resource is created: file opened.

Resources (opening order)fileopennetopen

The second resource is created. Resources are separated by semicolons and opened in the order written.

Resources (opening order)fileopennetin use

b.use(0): first “net in use” is printed, then 10 / 0.

Resources (opening order)fileopennetin useArithmeticException: / by zero

Exception thrown: the rest of try (“try end”) is skipped. But the resources are closed before catch.

Resources (opening order)fileopennetclosedArithmeticException: / by zero

Closing happens in reverse order: b, opened last, closes first (close()).

Resources (opening order)fileclosednetclosedArithmeticException: / by zero

Then a closes. Both resources were closed despite the exception.

Resources (opening order)fileclosednetclosedcaught

Now catch runs: the exception is caught.

Resources (opening order)fileclosednetclosed

finally runs last. Order: open → use → close (reversed) → catch → finally.

try (Resource a = new Resource("file");
     Resource b = new Resource("net")) {
  b.use(0);
  System.out.println("try end");
} catch (ArithmeticException e) {
  System.out.println("Error: " + e.getMessage());
} finally {
  System.out.println("finally");
}

finally

Nested try Blocks

try {
  // Outer try block
  try {
    // Inner try block
    // Code that may fail
  } catch (Exception e) {
    // Inner catch block
  } finally {
    // Inner finally block
  }
} catch (Exception e) {
  // Outer catch block
} finally {
  // Outer finally block
}

A try block can contain another try block. If an exception occurs in the inner try:

  1. If one of the inner try's catches matches, it runs.
  2. Otherwise the exception moves outward; the first matching catch is found and runs.
  3. If no catch matches, the exception leaves the method; if nobody catches it, the JVM's default handler ends the program.
  4. In every case, the finally (if any) at each level the exception passes through runs.

finally · Step by step

Nested try: The Exception Moves Outward

outer try {inner try { … s.length() }inner catch (ArithmeticException)inner finallyprintln("Outer try cont.")outer catch (NullPointerException)outer finallyprintln("Program goes on")

The outer try starts.

outer try {inner try { … s.length() }inner catch (ArithmeticException)inner finallyprintln("Outer try cont.")outer catch (NullPointerException)outer finallyprintln("Program goes on")

The inner try starts; s = null.

outer try {inner try { … s.length() }inner catch (ArithmeticException)inner finallyprintln("Outer try cont.")outer catch (NullPointerException)outer finallyprintln("Program goes on")

Calling a method on null → NullPointerException.

outer try {inner try { … s.length() }inner catch (ArithmeticException)✗inner finallyprintln("Outer try cont.")outer catch (NullPointerException)outer finallyprintln("Program goes on")

The inner catch only catches ArithmeticException: no match.

outer try {inner try { … s.length() }inner catch (ArithmeticException)✗inner finallyprintln("Outer try cont.")outer catch (NullPointerException)outer finallyprintln("Program goes on")

Before the exception leaves, the inner finally runs.

outer try {inner try { … s.length() }inner catch (ArithmeticException)✗inner finallyprintln("Outer try cont.")outer catch (NullPointerException)✓outer finallyprintln("Program goes on")

The exception reached the outer level; “Outer try cont.” was skipped. The outer catch matches.

outer try {inner try { … s.length() }inner catch (ArithmeticException)✗inner finallyprintln("Outer try cont.")outer catch (NullPointerException)✓outer finallyprintln("Program goes on")

The outer finally runs.

outer try {inner try { … s.length() }inner catch (ArithmeticException)✗inner finallyprintln("Outer try cont.")outer catch (NullPointerException)✓outer finallyprintln("Program goes on")

The exception was handled; the program continues normally.

public static void main(String[] args) {
  try {
    System.out.println("Outer try");
    try {
      System.out.println("Inner try");
      String s = null;
      System.out.println(s.length());
    } catch (ArithmeticException e) {
      System.out.println("Inner catch");
    } finally {
      System.out.println("Inner finally");
    }
    System.out.println("Outer try cont.");
  } catch (NullPointerException e) {
    System.out.println("Outer catch: NPE");
  } finally {
    System.out.println("Outer finally");
  }
  System.out.println("Program goes on");
}

Hierarchy

The Exception Hierarchy

  • Java's exception classes form a class hierarchy.
  • Throwable is the root of everything that can be thrown: only objects of Throwable and its subclasses can be thrown with throw and caught with catch.
  • Throwable has two direct subclasses: Error and Exception.
  • A catch block catches the named type and all its subclasses (a natural result of inheritance).
  • Java lets you define your own custom exception classes: classes for application-specific situations join this hierarchy.
Why a hierarchy?

Exceptions of one family can be caught with a single supertype: catch (IOException e) catches FileNotFoundException and other I/O errors alike.

Hierarchy

The Exception Class Tree

ThrowableErrorExceptionOutOfMemoryErrorStackOverflowErrorAssertionErrorserious system problemsother subclasses (checked)IOExceptionFileNotFoundExceptionSQLExceptionClassNotFoundExceptionParseExceptionInterruptedExceptionRuntimeExceptionArithmeticExceptionNullPointerExceptionClassCastExceptionIllegalArgumentExceptionNumberFormatExceptionIndexOutOfBoundsExceptionArrayIndexOutOfBoundsExceptionStringIndexOutOfBoundsException
checkedunchecked: RuntimeException and its subclassesunchecked: Error and its subclasses

Hierarchy

Error and Exception

Error

  • Signals that the program has hit a serious problem it cannot recover from.
  • Such situations usually cannot be handled and typically end the program.
  • Examples: extreme cases such as running out of memory (OutOfMemoryError), a call stack overflow, or a disk drive “vanishing”.
  • Catching them in application code is not recommended.

Exception

  • Conditions the program can anticipate and often recover from.
  • A missing file, a dropped network connection, invalid input, a null reference…
  • The type you are expected to handle with try-catch.
  • Its subclass RuntimeException mostly represents programmer errors.

Both derive from Throwable, so both can be thrown. But the family that “should be handled” is Exception.

Kinds of Exceptions

Kinds of Exceptions

Checked exceptions

Checked by the compiler at compile time; the programmer must handle or declare them. They cover situations known in advance to be possible.

Unchecked exceptions

Not checked at compile time; they show up at run time. RuntimeException, Error and their subclasses.

Kinds of exceptionsUser-definedBuilt-inCheckedUncheckedClassNotFoundExceptionInterruptedExceptionIOExceptionInstantiationExceptionSQLExceptionFileNotFoundExceptionArithmeticExceptionClassCastExceptionNullPointerExceptionArrayIndexOutOfBoundsExceptionArrayStoreExceptionIllegalThreadStateException… extends Exception→ checked… extends RuntimeException→ unchecked

Kinds of Exceptions

Checked Exceptions

  • Must be handled or declared by the code: the “catch or declare” rule.
  • Either list it with throws in the method header or handle it in a try-catch.
  • Derives from Exception but not from RuntimeException.
  • The rule is enforced at compile time: break it and the program won't compile.
  • Example: reading a file that doesn't exist. However correct the program is, the file may have been deleted, so the compiler demands a plan.

✗ Neither handled nor declared

public void readFile() {
  FileReader reader = new FileReader("data.txt");
}
error: unreported exception FileNotFoundException;
  must be caught or declared to be thrown

✓ Declared with throws

public void readFile() throws FileNotFoundException {
  // Read the file
  FileReader reader = new FileReader("data.txt");
}

Kinds of Exceptions

Handling a Checked Exception

public static void readFile2() {
  try {
    FileReader reader = new FileReader("data.txt");
    // Read the file
  } catch (FileNotFoundException e) {
    // Checked exception handled here
    System.err.println("File not found: " + e.getMessage());
    // Rethrow if needed:
    // throw e;
  }
}
Output (Windows; on Linux: No such file or directory)
File not found: data.txt (The system cannot find the file specified)
  • Here the method catches the exception itself; there is no throws in its signature. The caller doesn't have to do anything.
  • System.err: the error output stream. Most IDEs show it in red.
  • The message comes from the operating system, so it differs on Windows and Linux.
  • throw e;: a caught exception can be rethrown if needed (say, after logging it). The method must then declare throws FileNotFoundException again.

Kinds of Exceptions

Unchecked Exceptions

  • Exceptions you are not required to handle or declare.
  • They usually come from logic errors or programmer errors: dividing by zero, using null, going past an array's bounds.
  • No throws clause or try-catch is required; the compiler stays silent.
  • They derive from RuntimeException or Error.
  • The right fix is usually not to catch them but to prevent them: check the divisor before dividing and null before use.
public void divide(int num, int den) {
  // Unchecked: ArithmeticException
  int result = num / den;
}

Compiles; no throws needed. If den == 0, an exception occurs at run time.

public void divide(int num, int den) {
  if (den == 0) {   // prevention
    System.out.println("Divisor cannot be 0");
    return;
  }
  int result = num / den;
}

Kinds of Exceptions

Checked, Unchecked, Error

CheckedUncheckedError
SuperclassException (except RuntimeException)RuntimeExceptionError
Checked by compiler?Yes: handle or declareNoNo
Typical causeConditions outside the program (file, network, database)Programmer error (null, bounds, division)JVM / system problem
What to doCatch and recover, or pass on with throwsFix the code, validate inputUsually don't catch; end the program cleanly
ExamplesIOException, SQLException, ClassNotFoundExceptionNullPointerException, ArithmeticExceptionOutOfMemoryError, StackOverflowError

Throwing

Throwing an Exception

  • When the Java runtime hits an unexpected situation, it creates an exception object and throws it to notify higher-level code.
  • The programmer can do the same with the throw keyword.
  • An exception changes the normal flow: the lines after throw don't run; control jumps to a matching catch.
  • Many types can be thrown: IOException, NullPointerException, IllegalArgumentException, your own custom classes…
  • The caller can catch a thrown exception with try-catch. If it is never handled, the JVM ends the program and reports what went wrong and where.

Syntax

throw new Exception("This is an exception!");

new creates the exception object (the message goes to the constructor); throw throws it.

try {
  throw new Exception("This is an exception!");
} catch (Exception e) {
  System.out.println(e);
}
Output
java.lang.Exception: This is an exception!

Throwing

The Exception Type That Best Fits

class CustomException extends Exception {
  public CustomException(String message) {
    super(message);
  }
}
public static void check(int value)
    throws CustomException {
  if (value < 0) {
    // Check a condition and throw
    throw new CustomException("Value cannot be negative!");
  }
  // Value is OK: carry on
  System.out.println("Value OK: " + value);
}
// in main
try {
  check(5);
  check(-3);
  check(8);
} catch (CustomException e) {
  System.out.println("Caught: " + e.getMessage());
}
Output
Value OK: 5
Caught: Value cannot be negative!
  • Choose the exception class that best represents the situation.
  • For special scenarios you can create custom exception classes.
  • CustomException is a subclass of Exception, so it is checked. That is why the method signature needs throws CustomException.
  • Once check(-3) throws, the rest of try is skipped: check(8) is never called.

Throwing · Step by step

throw: An Exception Skips the Rest of try

Call stackmain()check(5)

main calls check(5) inside try; a new frame is pushed on the stack.

Call stackmain()check(5)

5 < 0 is false: the throw line is skipped.

Call stackmain()check(5)

“Value OK: 5” is printed; the method returns normally.

Call stackmain()check(-3)

Next call: check(-3).

Call stackmain()check(-3)

-3 < 0 is true.

Call stackmain()check(-3)CustomExceptionValue cannot be negative!

new creates the exception object and throw throws it. Line 5 doesn't run; the method has no catch, so its frame is discarded.

Call stackmain()

The exception reached main; the rest of try (check(8)) is skipped and a matching catch is found.

Call stackmain()

getMessage() returns the message given to the constructor.

Call stackmain()

catch is done; the program continues its normal flow. check(8) was never called.

static void check(int value) throws CustomException {
  if (value < 0) {
    throw new CustomException("Value cannot be negative!");
  }
  System.out.println("Value OK: " + value);
}
// in main
try {
  check(5);
  check(-3);
  check(8);
} catch (CustomException e) {
  System.out.println("Caught: " + e.getMessage());
}

Throwing

throw vs throws

throwthrows
PurposeThrows an exception (now)Declares the exceptions a method may throw (possibly later)
WhereIn the method body, as a statementIn the method signature, after the parameters
Followed byA single object: throw new X("…");One or more types: throws X, Y
Examplethrow new ArithmeticException("Division by zero");void divide(int x, int y) throws ArithmeticException

✗ throws can't be used in the body

if (x < 0) {
  throws new IllegalArgumentException("negative");
}
error: illegal start of expression

✗ Checked exception thrown without being declared

static void f(int x) {
  if (x < 0) throw new Exception("negative");
}
error: unreported exception Exception;
  must be caught or declared to be thrown

Throwing

Calling Methods That Throw

A file-reading method

public void readFile() throws FileNotFoundException {
  // Read the file
}

1) The caller handles it (preferred)

try {
  readFile();
} catch (FileNotFoundException e) {
  // Handle the missing file
  System.err.println("File not found: " + e.getMessage());
}

2) The caller declares it too (passes it on)

public void makeReport() throws FileNotFoundException {
  readFile();
}
  • When calling a method, consider the exceptions declared in its signature and pick a suitable strategy.
  • Put the call inside a suitable try-catch block.
  • Or have the caller declare the same type with throws; the problem moves up a level. This only postpones the problem, so it is less preferred than catching.
  • Even main can declare throws; an uncaught exception then ends the program.

Throwing · Step by step

Propagation: The Exception Unwinds the Call Stack

Call stackmain()

main calls compute(10) inside try.

Call stackmain()compute(10)

A compute frame is pushed on the stack.

Call stackmain()compute(10)

compute calls divide(10, 0).

Call stackmain()compute(10)divide(10, 0)

divide is now on top of the stack.

Call stackmain()compute(10)divide(10, 0)ArithmeticException/ by zero

10 / 0: the exception is born in divide. divide has no try → the rest of divide doesn't run and its frame is discarded.

Call stackmain()compute(10)ArithmeticException/ by zerodivide(10, 0)

The exception passes to the caller, compute. No try here either → “compute ended” is skipped and the frame is discarded.

Call stackmain()ArithmeticException/ by zerocompute(10)divide(10, 0)

The exception reaches main. The call is inside a try, so a matching catch is sought. The “Result” line is skipped.

Call stackmain()compute(10)divide(10, 0)

catch matches: the exception is caught and propagation stops.

Call stackmain()compute(10)divide(10, 0)

The program ends normally. Had nobody caught it, the JVM would have ended the program.

static int divide(int a, int b) {
  System.out.println("divide started");
  int s = a / b;
  System.out.println("divide ended");
  return s;
}
static int compute(int x) {
  System.out.println("compute started");
  int r = divide(x, 0);
  System.out.println("compute ended");
  return r;
}
public static void main(String[] args) {
  try {
    int result = compute(10);
    System.out.println("Result: " + result);
  } catch (ArithmeticException e) {
    System.out.println("main: " + e.getMessage());
  }
  System.out.println("Program ended");
}

Throwing

How Does the JVM Handle an Exception?

  1. The JVM (or throw) creates an exception object holding its type, its message and a stack trace of where it occurred.
  2. In the method where it occurred, the JVM looks for an enclosing try with a compatible catch.
  3. If none is found, the method ends at once (its finally runs, if any) and the exception passes to the calling method. The search continues down the call stack.
  4. If a matching catch is found, it runs; the program continues after the catch.
  5. If main doesn't catch it either, the JVM's default handler prints the stack trace and ends the program (that thread).
This search is called stack unwinding. Once the catch block ends, the caught exception object is no longer used and is cleaned up by the garbage collector.
main()try / catch ✓a()no catchb()no catchc()thrown herecalls → ← exception path

Runtime Exceptions

RuntimeException Classes

RuntimeException and its subclasses represent exceptions caused by programmer errors or logic errors. They are not checked at compile time and need not be handled; still, the programmer should deliberately prevent or handle them.

ClassWhen does it occur?Example
NullPointerExceptionUsing a member of a null referenceString s = null; s.length();
ArrayIndexOutOfBoundsExceptionIndex outside the array boundsint[] a = new int[3]; a[5] = 1;
ArithmeticExceptionInteger division by zero, overflow in exact arithmetic10 / 0
IllegalArgumentExceptionA method gets an invalid argumentnew ArrayList<>(-1)
NumberFormatExceptionConverting text that isn't a valid numberInteger.parseInt("abc")
ClassCastExceptionCasting an object to a type it doesn't have(Integer) obj

Runtime Exceptions

NullPointerException

  • Calling a method, accessing a field or taking length through a null reference causes this exception.
  • One of the most common bugs. To prevent it:
    • An explicit check: if (str != null)
    • Objects.requireNonNull(x, msg): if null, throws an NPE immediately with a meaningful message
    • Objects.requireNonNullElse(x, fallback) (Java 9+): returns the fallback if null
    • The Optional class (Java 8+): explicitly represents “there may be no value”
    • Libraries: Apache Commons Lang StringUtils offers null-safe string operations
String str = null;
int length = str.length();
Output (Java 14+ helpful message)
Exception in thread "main" java.lang.NullPointerException:
  Cannot invoke "String.length()" because "str" is null
Since Java 14 the message says which reference was null. The variable name appears when compiled with debug info (javac -g, IDEs); otherwise you see "<local1>".

Runtime Exceptions

Working Safely with null

1String str = null;
2int length = str.length();
3Objects.requireNonNull(str, "str must not be null");
4Optional<String> optionalStr = Optional.ofNullable(str);
5length = optionalStr.map(String::length).orElse(0);
6String defaultValue = Objects.requireNonNullElse(str, "0");
7if (str != null) {
8  System.out.println(str.length());
9}
10System.out.println("Ali".equals(str));
LineResult (each line tried on its own)
2NullPointerException: Cannot invoke "String.length()" because "str" is null
3NullPointerException: str must not be null
5length = 0 (no value → orElse(0))
6defaultValue = "0"
7–9Condition false; nothing printed, no exception
10false: the literal comes first, so a null argument is fine

"Ali".equals(str) is safe; str.equals("Ali") throws an NPE when str is null. Use requireNonNull at the start of methods to catch the error at its source with a clear message.

Runtime Exceptions

ArrayIndexOutOfBoundsException

  • Accessing an index outside the array's bounds: valid indexes are 0 … length − 1; a negative index is invalid too.
  • A member of the IndexOutOfBoundsException family. Different classes of that family may be thrown:
    • array (int[]), Vector, an Arrays.asList(...) list → ArrayIndexOutOfBoundsException
    • ArrayList.get → IndexOutOfBoundsException (the superclass)
    • String.charAt → StringIndexOutOfBoundsException
  • To catch them all: catch (IndexOutOfBoundsException e).

Prevention: bound the loop with length

int[] numbers = {1, 2, 3};
for (int i = 0; i < numbers.length; i++) {
  System.out.print(numbers[i] + " ");
}
Output
1 2 3
Most common cause: writing i <= arr.length. The last pass accesses arr[length] and throws.

Runtime Exceptions

Out of Bounds: Which Line, Which Exception?

1int[] numbers = {1, 2, 3};
2int value = numbers[5];
3ArrayList<String> list = new ArrayList<>();
4String svalue = list.get(5);
5Vector<Integer> vector = new Vector<>();
6value = vector.get(10);
7String[] names = {"Alice", "Bob", "Charlie"};
8svalue = Arrays.asList(names).get(5);
9String str = "Hello";
10char ch = str.charAt(10);
LineException thrown and its message
2ArrayIndexOutOfBoundsException
Index 5 out of bounds for length 3
4IndexOutOfBoundsException
Index 5 out of bounds for length 0
6ArrayIndexOutOfBoundsException
Array index out of range: 10
8ArrayIndexOutOfBoundsException
Index 5 out of bounds for length 3
10StringIndexOutOfBoundsException
Index 10 out of bounds for length 5

Each line tried on its own. An empty ArrayList may have capacity, but its size is 0; get checks against the size.

Runtime Exceptions

ArithmeticException

  • Represents an error during a mathematical operation; the best-known case is integer division by zero (/ and %).
  • The “exact” methods of Math throw on overflow: addExact, multiplyExact, toIntExact…
  • BigDecimal provides high-precision arithmetic; it throws on division by zero or when the quotient can't be represented exactly (1/3).
  • double operations don't throw: 10.0 / 0 → Infinity, Math.sqrt(-1) → NaN.
  • Random.nextInt(0) throws IllegalArgumentException, not ArithmeticException: the bound must be positive.
Silent overflow: when an ordinary int addition overflows, no exception occurs; the value wraps around:
Integer.MAX_VALUE + 1 → -2147483648.
If overflow must be detected, use Math.addExact.

Runtime Exceptions

Arithmetic Errors: Line by Line

1int result = 10 / 0;
2double dresult = Math.sqrt(-1);
3System.out.println(dresult);
4System.out.println(10.0 / 0);
5int t = Math.addExact(Integer.MAX_VALUE, 1);
6Random random = new Random();
7int randomNumber = random.nextInt(0);
8BigDecimal num1 = new BigDecimal("10");
9BigDecimal num2 = BigDecimal.ZERO;
10BigDecimal bresult = num1.divide(num2);
LineResult
1ArithmeticException: / by zero
3Prints NaN, no exception
4Prints Infinity, no exception
5ArithmeticException: integer overflow
7IllegalArgumentException: bound must be positive
10ArithmeticException: Division by zero

Each line tried on its own. With floating-point numbers, division by zero yields special values (Infinity, NaN) under IEEE 754 rules, so double results need their own checks (Double.isNaN).

Runtime Exceptions

IllegalArgumentException

  • Signals that a method received an invalid argument. It is an unchecked exception.
  • Checking arguments and throwing stops the error at its source.
  • Library examples:
    • Arrays.copyOfRange(d, 5, 2): start > end
    • new ArrayList<>(-1): negative capacity
    • setPriority(11) on a Thread: priority must be 1–10
    • new File(uri): the URI is not a file: URI
public void setAge(int age) {
  if (age < 0) {
    throw new IllegalArgumentException("Age cannot be negative");
  }
  this.age = age;
}
public void setName(String name) {
  if (name.length() < 3) {
    throw new IllegalArgumentException("Min 3 characters");
  }
  this.name = name;
}
Not every invalid case throws this: new FileReader("invalid/file/path") → FileNotFoundException; new Thread(null) throws nothing. Subclass: NumberFormatException.

Runtime Exceptions

Illegal Argument: Line by Line

1setAge(-5);
2setName("Al");
3int[] numbers = {1, 2, 3};
4Arrays.copyOfRange(numbers, 5, 2);
5List<Integer> list = new ArrayList<>(-1);
6File file = new File(URI.create("http://example.com/a.txt"));
7Thread thread = new Thread(task);
8thread.setPriority(11);
LineException thrown (each line on its own)
1IllegalArgumentException: Age cannot be negative
2IllegalArgumentException: Min 3 characters
4IllegalArgumentException: 5 > 2
5IllegalArgumentException: Illegal Capacity: -1
6IllegalArgumentException: URI scheme is not "file"
8IllegalArgumentException (no message)

A good message states the invalid value and what was expected: "Age cannot be negative: " + age. An exception with no message (line 8) makes debugging harder.

Runtime Exceptions

NumberFormatException

  • Occurs when text being converted to a number doesn't represent a valid number.
  • Integer.parseInt, Double.parseDouble, Float.parseFloat, Short.parseShort, Long.parseLong, Byte.parseByte and the valueOf methods can throw it.
  • It also occurs when the value is outside the type's range: Byte.parseByte("300").
  • A subclass of IllegalArgumentException.
  • User input always carries this risk: validate it first or catch the exception.
String strNumber = "abc";
int number = Integer.parseInt(strNumber);
strNumber = "123abc";
number = Integer.parseInt(strNumber);
String strDouble = "12.34abc";
double doubleValue = Double.parseDouble(strDouble);
String strShort = "45xyz";
short shortValue = Short.parseShort(strShort);
CallNumberFormatException message
Integer.parseInt("abc")For input string: "abc"
Integer.parseInt("123abc")For input string: "123abc"
Double.parseDouble("12.34abc")For input string: "12.34abc"
Short.parseShort("45xyz")For input string: "45xyz"

Runtime Exceptions

Safe Number Parsing

static int safeParse(String text, int fallback) {
  try {
    return Integer.parseInt(text.trim());
  } catch (NumberFormatException e) {
    return fallback;
  }
}
// in main
System.out.println(safeParse(" 42 ", 0));
System.out.println(safeParse("forty", 0));
System.out.println(safeParse("10.5", -1));
Output
42
0
-1
  • Parsing is checked in one place, a helper method; invalid input yields a default value.
  • trim() removes leading and trailing spaces: parseInt(" 42 ") alone would throw.
  • "10.5" is not an int; for decimals use Double.parseDouble.
  • Pick a default that can't be confused with a valid result; if it can, passing the exception to the caller is the better choice.

Runtime Exceptions · Step by step

parseInt and catch: Three Inputs

text·7·

First call: text " 7 " (spaces at both ends), fallback 0.

text·7·trim()7parseInt("7") = 7 → return 7

trim() drops the spaces; "7" becomes a number and 7 is returned from inside try.

textseven

Second call: "seven".

textseventrim()sevenNumberFormatException: For input string: "seven"

parseInt throws on text that isn't digits; return never ran.

textseventrim()sevencatch → return fallback = 0

catch matches: the fallback 0 is returned. The exception doesn't leave the method.

text7.5

Third call: "7.5", fallback −1.

text7.5trim()7.5NumberFormatException: For input string: "7.5"

A dot is not a digit: "7.5" is not a valid int.

text7.5trim()7.5catch → return fallback = -1

−1 is returned. The caller carries on with the fallback instead of an exception.

static int safeParse(String text, int fallback) {
  try {
    return Integer.parseInt(text.trim());
  } catch (NumberFormatException e) {
    return fallback;
  }
}
System.out.println(safeParse(" 7 ", 0));
System.out.println(safeParse("seven", 0));
System.out.println(safeParse("7.5", -1));

Runtime Exceptions

ClassCastException

  • Occurs when you cast an object to a type it is not.
  • What counts is the object's actual type, not the variable's: Object obj = "Hello" is a String object.
  • Raw collections (ArrayList, Map, Set) accept anything; the cast fails when an element of the wrong type is retrieved. Sorted collections (TreeSet, TreeMap) also throw when an incomparable element is added.
  • Prevention: generics (ArrayList<String>) catch the wrong type at compile time; check with instanceof before casting.
1Object obj = "Hello";
2Integer number = (Integer) obj;
3ArrayList list = new ArrayList();
4list.add("Hello");
5number = (Integer) list.get(0);
6Map map = new HashMap();
7map.put("key", "Value");
8Integer value = (Integer) map.get("key");
9Set set = new HashSet();
10set.add("Hello");
11value = (Integer) set.iterator().next();
12Object[] objArray = new String[5];
13Integer[] intArray = (Integer[]) objArray;

Lines 2, 5, 8, 11 and 13 each throw ClassCastException, for example:

class java.lang.String cannot be cast to class
java.lang.Integer

Runtime Exceptions

instanceof Before Casting

Classic form

Object obj = "Hello";
if (obj instanceof Integer) {
  Integer num = (Integer) obj;
  System.out.println("Number: " + num);
} else {
  System.out.println("obj is not an Integer");
}
Output
obj is not an Integer

Pattern matching (Java 16+)

if (obj instanceof Integer num) {
  System.out.println("Number: " + num);
}

With generics, at compile time

ArrayList<String> list = new ArrayList<>();
list.add("Hello");
Integer n = (Integer) list.get(0);
error: incompatible types: String cannot be
  converted to Integer
A compile error instead of a runtime exception: the bug is found earlier, without running the program. That's why generic types are preferred over raw types.

Checked Classes

Checked Exception Classes

They represent situations, mostly caused by conditions outside the program, that the code must handle and recover from properly. The compiler requires them to be handled.

ClassPackageWhen?
FileNotFoundExceptionjava.ioThe file to open doesn't exist or can't be opened
IOExceptionjava.ioGeneral input/output error (superclass)
SQLExceptionjava.sqlDatabase access error
ParseExceptionjava.textError while parsing text against a format
ClassNotFoundExceptionjava.langA class to be loaded by name was not found
InterruptedExceptionjava.langA waiting thread was interrupted (Thread.sleep)
NotSerializableExceptionjava.ioAn attempt to write a non-serializable object

Checked Classes

FileNotFoundException

try {
  FileReader fileReader = new FileReader("file.txt");
} catch (FileNotFoundException e) {
  // Handle the missing file
  System.out.println(e);
}
Output (no file, Windows)
java.io.FileNotFoundException: file.txt
  (The system cannot find the file specified)
  • Occurs when a file to be opened cannot be found (or is a folder, or can't be read).
  • A subclass of IOException; catch (IOException e) catches it too.
  • A relative path ("file.txt") is resolved against the program's working directory. In IDEs this is usually the project folder, so the file may be “in the wrong folder”.
  • Typical response: tell the user and ask for another name, or carry on with defaults.

Checked Classes

IOException

try {
  BufferedReader reader =
    new BufferedReader(new FileReader(path));
  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
  reader.close();
} catch (IOException e) {
  // Handle the I/O error
  e.printStackTrace();
}
Output (when notes.txt exists)
first line
second line
  • Represents a general I/O error; it has many subclasses such as FileNotFoundException.
  • Problem: if readLine() throws, reader.close() never runs; the file stays open (a resource leak).

✓ With try-with-resources

try (BufferedReader reader =
    new BufferedReader(new FileReader(path))) {
  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
} catch (IOException e) {
  System.out.println(e.getMessage());
}

Checked Classes

SQLException

try {
  Connection connection =
    DriverManager.getConnection("jdbc:mysql://localhost/school");
  PreparedStatement preparedStatement =
    connection.prepareStatement("SELECT user_id FROM users");
  // Run the query and process the results
  ResultSet resultSet = preparedStatement.executeQuery();
  while (resultSet.next()) {
    // Process the results
    System.out.println("User ID: " + resultSet.getInt("user_id"));
  }
  // Close the connection
  connection.close();
} catch (SQLException e) {
  // Handle the SQLException
  System.out.println(e);
}
  • Thrown when a database operation fails: no connection, bad SQL syntax, missing table, missing driver…
  • getMessage(), getSQLState() and getErrorCode() give details.
Output (no MySQL driver)
java.sql.SQLException: No suitable driver
found for jdbc:mysql://localhost/school

A connection is a resource too; close it with try-with-resources.

Checked Classes

ParseException and ClassNotFoundException

ParseException (java.text)

Thrown when text doesn't match the expected format during parsing.

try {
  SimpleDateFormat form =
    new SimpleDateFormat("dd/MM/yy");
  Date date = form.parse("01-01-2022");
} catch (ParseException e) {
  // Handle the parse error
  System.out.println(e);
}
Output
java.text.ParseException: Unparseable date: "01-01-2022"

The format expects /; the text has -.

ClassNotFoundException

Thrown when a class to be loaded by name (Class.forName) can't be found.

try {
  Class.forName("java.util.Scanner");
  System.out.println("Scanner loaded");
  // Try to load a missing class
  Class.forName("com.example.NonExistentClass");
} catch (ClassNotFoundException e) {
  System.out.println(e);
}
Output
Scanner loaded
java.lang.ClassNotFoundException:
  com.example.NonExistentClass

Checked Classes

NotSerializableException

class Point {               // not Serializable
  int x = 3, y = 4;
}
// in main
try (ObjectOutputStream outputStream =
    new ObjectOutputStream(new ByteArrayOutputStream())) {
  // Try to serialize the object
  Point notSerializableObj = new Point();
  outputStream.writeObject(notSerializableObj);
} catch (NotSerializableException e) {
  System.out.println(e);
} catch (IOException e) {
  System.out.println("Other I/O error: " + e);
}
Output
java.io.NotSerializableException: Point
  • Serialization: converting an object to a byte stream (to write it to a file or send it over a network) and restoring it later.
  • A class that implements Serializable is serializable; writing an object of a class that doesn't throws this exception.
  • An (indirect) subclass of IOException, so its catch goes before the IOException catch.

✓ Fix

class Point implements Serializable {
  int x = 3, y = 4;
}

Error Classes

Error Classes

  • Unchecked types for system-level problems that fundamentally affect the program's normal operation.
  • They usually stem not from a line of application code but from the state of the JVM and its environment.
  • Thrown by the JVM; handling or declaring them is not recommended. Letting the program end cleanly is the better approach.
  • Still, since they are Throwables, they can technically be caught.
ErrorWhen?
OutOfMemoryErrorHeap memory is exhausted
StackOverflowErrorThe call stack overflowed: usually infinite recursion
AssertionErrorAn assert condition is false (only with -ea)
NoClassDefFoundErrorA class present at compile time is missing at run time
mainrecurserecurserecurserecurserecurserecurse…recursestack limiteach call adds a frame → StackOverflowErrorno base case: calls never return

Error Classes

Error Examples

static void recurse() {
  recurse();         // no base case
}
public static void main(String[] args) {
  try {
    recurse();
  } catch (StackOverflowError e) {
    System.out.println("SOE -> " + e);
  }
  try {
    long[] arr = new long[Integer.MAX_VALUE];
  } catch (OutOfMemoryError e) {
    System.out.println("OOM -> " + e);
  }
  int age = -5;
  assert age >= 0 : "Negative age: " + age;
  System.out.println("assert passed");
}
java Demo
SOE -> java.lang.StackOverflowError
OOM -> java.lang.OutOfMemoryError: Requested array size exceeds VM limit
assert passed
java -ea Demo
SOE -> java.lang.StackOverflowError
OOM -> java.lang.OutOfMemoryError: Requested array size exceeds VM limit
Exception in thread "main" java.lang.AssertionError: Negative age: -5
  • If recursion has no base case, every call adds a new frame until the stack is full.
  • assert is disabled by default; enable it with -ea. It checks assumptions during development. (Catching here is for demonstration only.)

Custom Exceptions

Custom Exception Classes

public class MyException extends Exception {
  // Constructor
  public MyException(String message) {
    super(message);
  }
}
SuperclassResult
extends ExceptionChecked: the caller must handle it; recoverable business-rule violations
extends RuntimeExceptionUnchecked: misuse, programmer error
ThrowableExceptionRuntimeExceptionMyExceptioncheckedunchecked
  • Developers can create custom exception classes to manage unexpected situations specific to their programs.
  • An object of any class extending Throwable can be thrown. Usually, though, you extend Exception or RuntimeException, not Error or Throwable directly.
  • The constructor passes the message up with super(message), so getMessage() works.
  • End the name with …Exception; it should describe the situation.
  • You can add extra fields (a missing amount, a bad value): an exception is an ordinary class.

Custom Exceptions

Throwing and Catching a Custom Exception

public class MyExceptionTest {
  public static void main(String[] args) {
    try {
      doWork();
    } catch (MyException e) {
      System.out.println("Caught: " + e.getMessage());
    }
  }
  public static void doWork() throws MyException {
    if (true) {
      throw new MyException("Custom error occurred.");
    }
  }
}
Output
Caught: Custom error occurred.
  • MyException extends Exception, so it is checked: throws MyException is required in the signature of doWork().
  • main wraps the call in try, choosing to “handle” it.
  • if (true) is only for the demo: code after an unconditional throw would cause an “unreachable statement” error.
  • In real programs the condition checks a business rule: is the balance enough, is the grade within 0–100, is the user name empty…

Custom Exceptions · Step by step

Custom Exception: A Bank Account

Stack: mainHeapacctAccountbalance = 100.0

The Account object is created on the heap; acct refers to it.

Stack: mainHeapacctAccountbalance = 100.0

withdraw(30): is 30 > 100? No; no exception.

Stack: mainHeapacctAccountbalance = 70.0

The balance becomes 70.0 and is printed.

Stack: mainHeapacctAccountbalance = 70.0

withdraw(90): is 90 > 70? Yes.

Stack: mainHeapacctAccountbalance = 70.0LowBalanceExceptionmsg: "Insufficient funds"deficit = 20.0

An exception object is created on the heap (message and deficit = 20.0) and thrown. The balance is unchanged.

Stack: mainHeapacctAccountbalance = 70.0LowBalanceExceptionmsg: "Insufficient funds"deficit = 20.0e

withdraw's frame is discarded; withdraw(10) is skipped. catch matches: e refers to the same object.

Stack: mainHeapacctAccountbalance = 70.0LowBalanceExceptionmsg: "Insufficient funds"deficit = 20.0e

The exception object's data is used. An exception is just an ordinary object.

class Account {
  private double balance;
  Account(double balance) { this.balance = balance; }
  public void withdraw(double amount)
      throws LowBalanceException {
    if (amount > balance) {
      throw new LowBalanceException(
        "Insufficient funds", amount - balance);
    }
    balance -= amount;
    System.out.println("Balance: " + balance);
  }
}
// in main
Account acct = new Account(100);
try {
  acct.withdraw(30);
  acct.withdraw(90);
  acct.withdraw(10);
} catch (LowBalanceException e) {
  System.out.println(e.getMessage()
    + ", deficit: " + e.getDeficit());
}

Custom Exceptions

A Custom Exception That Carries Data

class LowBalanceException extends Exception {
  private double deficit;

  public LowBalanceException(String msg, double deficit) {
    super(msg);            // kept in Throwable
    this.deficit = deficit;
  }

  public double getDeficit() {
    return deficit;
  }
}
  • The class used in the previous trace: besides the message, it carries the missing amount.
  • The catching code can use it to respond sensibly: “You are 20 TL short; try anyway?”
  • A return code like -1 could never carry this much information.
  • A checked type was chosen: insufficient balance is a foreseeable situation the caller must deal with.

Stack Trace

Stack Trace

  • A report of which method calls were active and where the exception occurred.
  • It holds the exception's type and message, and for each call the class and method name, the file name and the line number.
  • For an uncaught exception the JVM prints it to the console (System.err); you can also print it with e.printStackTrace().
  • It is the most important clue for understanding and fixing a bug.
Exception in thread "main" java.lang.NullPointerException
    at com.example.MyClass.myMethod(MyClass.java:10)
    at com.example.MyClass.main(MyClass.java:6)

Reading it: main (line 6) called myMethod; the exception occurred at line 10 of myMethod. com.example is the package, MyClass the class.

Stack Trace

Reading a Stack Trace

1public class TraceDemo {
2  static int len(String text) {
3    return text.length();
4  }
5  static void show(String name) {
6    System.out.println(name + ": " + len(name));
7  }
8  public static void main(String[] args) {
9    show("Ali");
10    show(null);
11    System.out.println("Done");
12  }
13}
  1. First line: type and message: text is null.
  2. First at: where the exception was born (line 3).
  3. Reading down, the call chain: main (10) → show (6) → len (3).
  4. Look at your own lines first; the real cause is often further down: line 10 passed the null.
Output
Ali: 3
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "text" is null
    at TraceDemo.len(TraceDemo.java:3)
    at TraceDemo.show(TraceDemo.java:6)
    at TraceDemo.main(TraceDemo.java:10)

Stack Trace · Step by step

Where Does a Stack Trace Come From?

Call stack (rightmost on top)main

main calls show("Ali") at line 9.

Call stack (rightmost on top)mainshow

show calls len(name) at line 6. Each frame remembers its current line.

Call stack (rightmost on top)mainshowlen

"Ali".length() = 3 is returned; the frame is removed.

Call stack (rightmost on top)mainshow

“Ali: 3” is printed and show ends.

Call stack (rightmost on top)main

main calls show(null) at line 10.

Call stack (rightmost on top)mainshow

null is passed as an argument; no problem yet.

Call stack (rightmost on top)mainshowlenNullPointerException

null.length(): an NPE is thrown. The stack now holds three frames: len:3, show:6, main:10.

Stack trace = snapshot of the stackat len(TraceDemo.java:3)at show(TraceDemo.java:6)at main(TraceDemo.java:10)

When the exception object is born, it records the stack: each frame becomes an at line, the top one first.

Stack trace = snapshot of the stackat len(TraceDemo.java:3)at show(TraceDemo.java:6)at main(TraceDemo.java:10)

Nobody caught it: all three frames were discarded; the JVM printed the stack trace and ended the program. “Done” is never printed.

public class TraceDemo {
  static int len(String text) {
    return text.length();
  }
  static void show(String name) {
    System.out.println(name + ": " + len(name));
  }
  public static void main(String[] args) {
    show("Ali");
    show(null);
    System.out.println("Done");
  }
}

Stack Trace

Best Practices for Exception Handling

Catch specific types

Where possible, catch the expected type instead of catch (Exception e), and respond to each kind appropriately.

Don't swallow exceptions

An empty catch { } hides the error. At least log it or tell the user.

Close resources

Close files, connections and other resources with try-with-resources or finally.

Prevent what you can

Check for null, bounds and zero; fix the code instead of catching RuntimeException.

Not for control flow

Don't use exceptions for ordinary tasks such as leaving a loop; exceptions are for exceptional situations.

Meaningful messages

State the bad value and what was expected: "Grade must be 0-100: 120".

Handle in the right place

Catch an exception where it can be resolved; otherwise pass it on with throws.

Log them

Logging exceptions to a file makes it easier to trace errors later.

Stack Trace

final, finally and finalize

What?Role
finalKeywordVariable: can't be reassigned · method: can't be overridden · class: can't be subclassed
finallyKeyword (block)Cleanup block after try that runs whether or not an exception occurs
finalize()Method of ObjectThe garbage collector could call it before removing an object. When it runs is unpredictable; deprecated since Java 9.
Similar names, completely different jobs. For resource cleanup, use try-with-resources or finally, not finalize().

Summary

Summary

ConceptKey point
ExceptionDisrupts normal flow at run time; an object with type, message and location
try / catchRisky code in try; the first matching catch runs, rest of try skipped
catch orderSubclass before superclass; the reverse won't compile. A | B (Java 7+)
finallyAlways runs, even before return; for cleanup
try-with-resourcestry (Resource r = …): an AutoCloseable resource closes itself
HierarchyThrowable → Error | Exception → … RuntimeException
CheckedException (not Runtime): handle or declare with throws
UncheckedRuntimeException, Error: not required; prevent
throw / throwsThrow (body, object) / declare (signature, types)
PropagationUncaught exception passes to the caller; if main doesn't catch it, the program ends
Custom exceptionclass X extends Exception + super(message)
Stack traceType + message, then the call chain; the first at line is the origin

Summary

Common Mistakes

Forgetting a checked exception

new FileReader(name) with no try/throws: unreported exception FileNotFoundException; must be caught or declared to be thrown.

General catch first

catch (Exception e), then catch (ArithmeticException e): exception ArithmeticException has already been caught.

Catching what is never thrown

catch (FileNotFoundException e) on a try with no file operation: exception FileNotFoundException is never thrown in body of corresponding try statement.

A lone try

A try with no catch or finally: 'try' without 'catch', 'finally' or resource declarations.

Code after throw

A line right after throw in the same block: unreachable statement.

Using a try variable outside

Printing result, declared inside try, after the block: cannot find symbol. Declare it before the try.

Swallowing the exception

catch (Exception e) { } compiles, but the error vanishes without a trace.

Throwing a string

throw "error"; → incompatible types: String cannot be converted to Throwable.

Summary

Practice Problems (1)

Problem 1: What is the output?

static int f() {
  try {
    System.out.print("A");
    int x = 5 / 0;
    System.out.print("B");
    return 1;
  } catch (ArithmeticException e) {
    System.out.print("C");
    return 2;
  } finally {
    System.out.print("D");
  }
}
// in main
System.out.println(" " + f());

Problem 2: What is the output?

try {
  String s = "12a";
  int n = Integer.parseInt(s);
  System.out.println("Number: " + n);
} catch (IllegalArgumentException e) {
  System.out.println("IAE");
} catch (Exception e) {
  System.out.println("Exception");
}

Problem 3

What happens if the two catch blocks in Problem 2 swap places?

Show answers
  1. ACD 2: “A”; the division throws (B and return 1 are skipped); catch prints “C” and prepares 2; finally prints “D”; 2 is returned.
  2. IAE: NumberFormatException is a subclass of IllegalArgumentException.
  3. Compile error: exception IllegalArgumentException has already been caught.

Summary

Practice Problems (2)

Problem 4: What is the output?

static void a() {
  System.out.print("a1 ");
  b();
  System.out.print("a2 ");
}
static void b() {
  System.out.print("b1 ");
  throw new IllegalStateException("!");
}
// in main
try {
  a();
  System.out.print("m ");
} catch (IllegalStateException e) {
  System.out.print("caught" + e.getMessage());
} finally {
  System.out.println(" end");
}

The exception is born in b(); neither b() nor a() has a try. Which prints run and which are skipped? When does finally run?

Show answer

a1 b1 caught! end

The exception travels b → a → main: “a2” and “m” are skipped. The catch in main catches it, then finally prints “ end” and ends the line.

Summary

Practice Problems (3)

Problem 5: Final value of sum?

int[] d = {4, 0, 2};
int sum = 0;
for (int i = 0; i <= d.length; i++) {
  try {
    sum += 12 / d[i];
  } catch (ArithmeticException e) {
    sum += 100;
  } catch (ArrayIndexOutOfBoundsException e) {
    sum += 1000;
  }
}
System.out.println(sum);

Problem 6: What is the output?

try {
  throw new RuntimeException("X");
} finally {
  System.out.println("F");
}
Show answers
  1. 1109: 12/4 = 3, 12/0 → +100, 12/2 = 6, d[3] → +1000. Each pass has its own try, so the loop keeps going.
  2. First F, then Exception in thread "main" java.lang.RuntimeException: X: finally runs, but the exception is not caught, so the program ends.

Summary

Exercises (1)

  1. Write int readAge(String text): if the text isn't a number, let NumberFormatException occur; if negative, throw IllegalArgumentException. Use two catches to print messages for "20", "-3", "twenty".
  2. Write a checked exception InvalidGradeException and setGrade(int grade), which throws it for grades outside 0–100.
  3. In Exercise 1, what if the catch order is IllegalArgumentException, then NumberFormatException?
Answers / hints
  1. int age = Integer.parseInt(text); if (age < 0) throw new IllegalArgumentException("Negative age: " + age); return age; · Output: Age: 20, Negative age: -3, Not a number: twenty. The NFE catch must come first.
  2. class InvalidGradeException extends Exception { … super(msg); } · void setGrade(int grade) throws InvalidGradeException { if (grade < 0 || grade > 100) throw new InvalidGradeException("Grade must be 0-100: " + grade); … } · setGrade(120) → Grade must be 0-100: 120.
  3. Compile error: exception NumberFormatException has already been caught (NFE is a subclass of IAE).

Summary

Exercises (2)

  1. Classify as checked or unchecked: IOException, NumberFormatException, SQLException, NullPointerException, FileNotFoundException, ClassCastException, StackOverflowError.
  2. Rewrite code that closes a BufferedReader in finally using try-with-resources.
  3. What should double average(int[] grades) do for an empty array? Return 0 or throw an exception? Which one?
Answers / hints
  1. Checked: IOException, SQLException, FileNotFoundException · unchecked: NumberFormatException, NullPointerException, ClassCastException, StackOverflowError (Error).
  2. try (BufferedReader r = new BufferedReader(new FileReader(path))) { … } catch (IOException e) { … }: close() is called automatically.
  3. 0 could be confused with a valid average (like the −1 return code). An empty array is an invalid argument: throw new IllegalArgumentException("Empty array");

Summary

References

  • Oracle, The Java Tutorials: Lesson: Exceptions (Catching and Handling Exceptions; The try-with-resources Statement; Unchecked Exceptions — The Controversy).
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 11: Exceptions; 14.20 The try statement.
  • Oracle, Java SE 21 API Documentation: java.lang.Throwable, Exception, RuntimeException, Error.
  • P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 11: Exception Handling: A Deeper Look).
  • K. Sierra, B. Bates and T. Gee, Head First Java, 3rd ed., O'Reilly (Risky Behavior: exception handling).
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapter 7: Exceptions, Assertions, and Logging).
  • J. Bloch, Effective Java, 3rd ed., Addison-Wesley (Chapter 10: Exceptions, Items 69–77).

The End

Chapter 6: Exceptions
Previous: Chapter 5: Collections · Next: Chapter 7: Testing and Debugging
1 / 1 Sercan KÜLCÜ. All rights reserved.