• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Not every method can handle every error that occurs within it. Sometimes the right response is to notify the caller that something went wrong and let the caller decide how to handle it. Without a standard way to declare and propagate exceptions, error information would be lost.

Core Idea

The throw keyword manually creates and throws an exception. The throws keyword in a method signature declares that the method may throw one or more checked exceptions, letting callers know what to expect. throw is used inside the method body; throws is part of the method declaration.

How It Works

When throw new SomeException() executes, the JVM unwinds the call stack looking for a matching catch block. The throws clause in the method signature is a compile-time contract: callers must either catch the declared exceptions or add them to their own throws clause.

Visual Explanation

java_throw_throws MethodA methodA() throws IOException Throw throw new IOException() MethodA->Throw inside MethodB methodB() {  try { methodA(); }  catch (IOException e) { ... } } Catch Caught in methodB Handler executes MethodB->Catch Propagate Exception Propagates Up Call Stack Throw->Propagate Propagate->Catch matching catch found

Semantic Network

semantic_throw_throws THIS Throw & Throws HIER Exception Hierarchy THIS--HIER built from TC Try-Catch-Finally THIS--TC related CUST Custom Exceptions THIS--CUST builds into OVER Method Overriding THIS--OVER related

Key Properties

  • throw: Takes a Throwable instance (or subclass), never returns normally
  • throws: Lists checked exception types a method may propagate
  • RuntimeException: Does not need throws — unchecked by design
  • Override rules: Subclass method cannot throw a broader checked exception than the parent override

Connections

Edge Cases & Gotchas

  • Throws for RuntimeException: Legal but pointless — the compiler doesn’t enforce it
  • Overriding and throws: Subclass cannot add new checked exception types to throws clause
  • Exception chaining: Use throw new Cause(e) or initCause() to wrap exceptions
  • throws Exception: Too broad — defeats the purpose of checked exceptions