8.12. Exceptions

The Java programming language has a very nice error-handling system: exceptions. Exceptions can be “thrown” (generated) in one block of code and “caught” (handled) in an outer block or in a method that called the current one. Java exceptions differ from C++ exceptions in two major ways. The first major difference is that the exception-handling construct (try/catch) has a finally clause that always gets executed, regardless of whether or not an exception was thrown. The second significant difference is that you can require users of your methods to handle exceptions your methods generate; if they fail to do that, their code will not compile.

Basic Form

The simplest form of exception handling is a block of the following form:

Get Core Web Programming, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.