Exceptions
Why exceptions are needed
Even a correct program sometimes encounters a situation where it cannot continue in the usual way: a file is missing, data turns out to be invalid, a connection is interrupted, or called code reports a problem. The exceptions section will teach you not to ignore such situations, but to handle them predictably and clearly.
What matters here is not a single language construct, but an entire system: what problems code can report, how information about a problem can be passed further, and where it is best handled. You will need this knowledge in almost any application — from small programs to server-side services.
What the section covers
- Exception hierarchy. You will learn how exceptions are organized in Java and why their place in the hierarchy affects how you work with them.
- Try, catch, and finally. You will learn to isolate code where a problem may occur, handle it, and perform actions that must happen regardless of the result.
- Throw and throws. You will see how to report an error situation yourself and how to indicate that a method may pass an exception to the calling code.
- Checked and unchecked exceptions. You will understand why Java treats different groups of exceptions differently and how that affects method code.
- Custom exceptions. You will learn to create exceptions that describe problems specific to your application's domain.
- Try-with-resources. You will learn a convenient way to safely work with resources that need to be closed after use.
- Exception handling best practices. You will bring the individual mechanisms together into a clean style: where to catch exceptions, what information to preserve, and which approaches are better avoided.
How the topics fit together
First, you will get familiar with the overall exception system, then learn to catch and create exceptions. After that, you will explore the differences between their groups and move on to custom types and resource handling. At the end of the section, this knowledge will come together as practical rules that help you write code where errors are not hidden and do not turn into unexpected failures elsewhere in the program.