Phase XII
When Things Go Wrong
Every method you have written so far assumed everything works.
A file that is not there, a number that will not parse, a network that drops. Java splits these into the ones the compiler forces you to think about and the ones it does not, and the line between them is the single most argued about decision in the language. This phase is also where you find out that a return inside finally can swallow an exception whole, and that the stack trace you have been ignoring is the most useful thing on the screen.
When you finish this phase you can
- Read a stack trace from the bottom up and find the line that matters
- Say what separates an Error from an Exception, and why you catch neither by accident
- Explain checked and unchecked exceptions, and the argument against checked ones
- Use try-with-resources and say what it does that finally could not
- Write a custom exception that carries the information the caller needs
- Say what happens to an exception when finally returns
- 12.1Exceptions, Errors, and the Stack TraceA method that fails has to tell the one that called it. Returning a value cannot do that job, so Java unwinds the call stack instead, and the wall of text it prints is a map of exactly how it got there.ExceptionStack trace
- 12.2Checked, Unchecked, and Exceptions of Your OwnTwo things can fail the same way and the compiler treats them completely differently. The rule is real, the reasoning behind it is contested, and every language designed after Java went the other way.Checked exception