"throw" and "throws"
throw and throws look similar but solve different problems. throw is the instruction that sends one concrete exception object into the runtime. throws is a method declaration that tells callers which checked exceptions may leave the method. Understanding the difference prevents two common mistakes: expecting throws to perform handling and using throw as if it were a type declaration.
Creating and throwing an exception
throw appears inside executable code. It is useful when the method itself detects that its input or state violates a rule.
static void requirePositive(long userId) {
if (userId <= 0) {
throw new IllegalArgumentException("userId must be positive");
}
}
The expression after throw must produce a Throwable object. The statement stops the current path immediately: code after it in the same branch is unreachable. The message should describe the invalid condition and, when safe, include the relevant value or identifier. Never put passwords, tokens, or personal data into an exception message.
Declaring a checked failure
throws belongs in the method signature. It is required when a checked exception can escape the method.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
static String loadText(Path path) throws IOException {
return Files.readString(path);
}
The declaration does not catch, create, or throw the exception. It makes the method's failure contract visible to callers and moves the decision upward. A caller must then catch IOException or declare it too. Unchecked exceptions may also be written in throws for documentation, but the compiler does not require callers to handle them.
| Construct | Where it appears | What it does |
|---|---|---|
throw new ... |
Method body | Throws one concrete object now |
throws IOException |
Method declaration | Declares a checked failure that may escape |
catch (...) |
Method body | Handles a matching object |
cause |
Exception constructor | Preserves the lower-level reason |
Choosing the boundary
Throw an exception close to the rule that was violated. A domain service should reject an impossible state instead of returning false that the caller may forget to check. Do not throw from a method merely to signal an ordinary alternative such as “search returned no rows”; use the return type and contract appropriate for that case.
Declare or propagate a checked exception when the caller has a real recovery decision. At an application boundary, translate a low-level failure into a domain exception while preserving the cause:
try {
return Files.readString(path);
} catch (IOException ex) {
throw new ConfigurationLoadException("Cannot load configuration", ex);
}
Use names that identify the failed operation or domain rule: UserNotFoundException, ConfigurationLoadException, and InvalidOrderStateException are more useful than FailureException. The suffix Exception is conventional, and the message should explain the instance, not repeat the class name.
Glossary
- bytecode
- Platform-independent compiled code that the JVM can execute.
- class
- A blueprint that defines fields and methods for objects in object-oriented programming.
- object
- A runtime instance of a class with its own state and behavior.
- method
- A named block of behavior that belongs to a class or object and can be called by code.
- field
- A variable stored inside a class or object that represents part of its state.
- constructor
- A special method-like block used to create and initialize a new object.
- package
- A namespace that groups related Java classes and helps organize code.
- interface
- A contract that defines methods a class can implement without prescribing all internal details.
- generics
- A language feature that lets code work with types as parameters while preserving type safety.
- type erasure
- The Java compiler process that removes most generic type details from runtime bytecode.
- collection
- A data structure that stores a group of elements and provides operations over them.
- list
- An ordered collection where elements have positions and duplicates are allowed.
- set
- A collection that stores unique elements and is commonly used for membership checks.
- map
- A key-value data structure where each key points to a value.
- queue
- A collection designed for processing elements in a defined order, often first-in-first-out.
- lambda
- A compact function-like expression used to pass behavior as data.
- functional interface
- An interface with one abstract method, suitable for lambdas and method references.
- stream
- A Java API for processing data sequences with operations such as map, filter, and reduce.
- optional
- A container object that represents a value that may or may not be present.
- thread
- An independent path of execution inside a running program.
- synchronization
- Coordination that protects shared data when multiple threads access it.
- heap
- The runtime memory area where Java objects are allocated.
- stack
- The runtime memory area that stores method calls, local variables, and call frames.
- garbage collector
- A JVM component that automatically frees memory occupied by objects no longer reachable.
- memory leak
- A situation where memory remains occupied because objects are still referenced but no longer useful.