Java Exceptions: quick revision, 14 bites
All 14 revision bites from this kit, free and with no sign-up.
What is an Exception?
An unexpected event during program execution.
An **exception** is an event that disrupts the normal flow of a program's instructions. In Java, exceptions are objects that describe an error or unexpected condition. They can arise from user input, hardware failures, or programming bugs. Handling exceptions allows the program to continue or fail gracefully.
Takeaway. Exceptions are runtime disruptions that can be managed to keep programs stable.
Exception Hierarchy
All exceptions inherit from Throwable.
The root of the exception hierarchy is the **Throwable** class. It has two main subclasses: **Exception** (for recoverable conditions) and **Error** (for serious problems like `OutOfMemoryError`). `Exception` is further divided into **checked** and **unchecked** exceptions.
Takeaway. Understanding the hierarchy helps in catching the right exception type.
Checked vs Unchecked Exceptions
Compiler enforces checked, not unchecked.
**Checked exceptions** are checked at compile time; the compiler forces you to handle them (e.g., `IOException`). **Unchecked exceptions** occur at runtime and are not checked by the compiler (e.g., `ArithmeticException`). They are subclasses of `RuntimeException`.
Takeaway. Checked exceptions demand handling; unchecked exceptions are optional to handle.
Try-Catch Block
The core mechanism to handle exceptions.
The **try-catch** block is used to handle exceptions. Code that might throw an exception goes inside the `try` block. If an exception occurs, it is caught by the corresponding `catch` block. The `catch` block can specify the exception type to handle.
Takeaway. Try-catch allows graceful handling of runtime errors.
Finally Block
Code that always executes, even on exception.
The **finally** block is optional and always executes regardless of whether an exception is thrown or caught. It is typically used for cleanup activities like closing files or releasing resources. Even if a `return` statement is present in `try` or `catch`, the `finally` block runs before the method returns.
Takeaway. Finally ensures critical cleanup code runs no matter what.
Throw and Throws
Explicitly throw or declare exceptions.
The **throw** keyword is used to explicitly throw an exception from a method or block. The **throws** keyword is used in a method signature to declare that the method might throw one or more exceptions. This is mandatory for checked exceptions that are not handled within the method.
Takeaway. Throw sends an exception; throws declares it for the caller to handle.
Catching Generic Exception
Avoid catching Exception or Throwable broadly.
Catching **Exception** or **Throwable** is a common mistake because it hides specific error types and can catch unexpected errors like `OutOfMemoryError`. Always catch the most specific exception class possible. This makes the code more robust and easier to debug.
Takeaway. Catch specific exceptions to avoid masking errors.
Multiple Catch Blocks
Handle different exceptions differently.
You can have multiple `catch` blocks to handle different exception types separately. The order matters: catch specific exceptions before their superclasses. Java 7 introduced the multi-catch feature to catch multiple types in one block.
Takeaway. Multiple catch blocks allow tailored responses to different errors.
Try-With-Resources
Auto-close resources safely.
**Try-with-resources** automatically closes resources that implement `AutoCloseable` (e.g., files, sockets). It was introduced in Java 7 and reduces boilerplate code. The resource is closed automatically at the end of the try block, even if an exception occurs.
Takeaway. Try-with-resources simplifies resource management and prevents leaks.
Custom Exceptions
Create your own exception classes.
You can define **custom exceptions** by extending `Exception` (for checked) or `RuntimeException` (for unchecked). This helps in providing specific error messages and handling for your application's domain. Custom exceptions should include constructors that call the superclass constructor.
Takeaway. Custom exceptions make error handling more meaningful.
Order of Catch Blocks
Specific exceptions must come first.
In multiple catch blocks, the order is crucial. If a catch block for a superclass appears before a subclass, the subclass catch will never be reached, causing a compile-time error. Always place the most specific exception first.
Takeaway. Catch specific exceptions before general ones to avoid compile errors.
Remembering Throw vs Throws
Throw does; Throws declares.
A simple trick: **throw** is the action (like throwing a ball), **throws** is the declaration (like a sign saying 'may throw'). Use `throw` inside a method, and `throws` in the method signature.
Takeaway. Throw is the act; throws is the promise.
Checked Exceptions in Java
Java is unique in requiring checked exceptions.
Java is one of the few languages that enforce **checked exceptions** at compile time. This forces developers to handle or declare them, promoting robust error handling. Other languages like C# and Python do not have this requirement.
Takeaway. Checked exceptions are a distinctive Java feature.
Exception Handling as Safety Net
Like a safety net for a tightrope walker.
Think of exception handling as a **safety net** for a tightrope walker. The `try` block is the walk, `catch` is the net that catches falls, and `finally` is the cleanup after the performance. Without it, a fall would be fatal.
Takeaway. Exception handling catches errors before they crash the program.
Your notes can be a kit like these
Every kit here was made from real study material. Point Veda at a chapter, a PDF, a photo or a link and get notes, flashcards, practice MCQs, games and a scored test — free, in 42 languages.
- Chapter notes
- Flashcards
- Practice MCQs
- Scored tests
- Exam prep
Get Veda free See what students get
Free to start · No ads · Works in 42 languages