Exception handling
In short: Exception handling means catching runtime errors and dealing with them in a controlled way instead of letting the program crash. The error is “thrown” as an object and “caught” at a suitable place.
In more detail: Normal code and error handling are kept apart. When something goes wrong (file missing, index too large, network gone), an exception is raised. It travels up the call stack until a matching handler deals with it. If nobody catches it, the program ends with an error message and a stack trace.
In detail
- Raising: with throw and throws.
- Catching: with try/catch/finally.
- Kinds: checked exceptions must be handled, unchecked ones need not. Java makes this split, many other languages only have unchecked ones.
- Typical exceptions: IllegalArgumentException, EOFException (EOF), ArrayIndexOutOfBoundsException, NullPointerException.
- Good practice: only catch what you can sensibly handle. Never catch and do nothing. Write meaningful messages. Always release resources (try-with-resources).
- Alternative: some languages (Go, Rust) return errors as values instead of throwing.
See also: Exceptions, Multiple exceptions