7.3. Creating a method that throws an exception

[8.4] Create and invoke a method that throws an exception

In this section, you’ll explore the need to create methods that throw exceptions. You’ll also work with the throw and throws keywords to define methods that throw exceptions.

Why do you need methods that throw exceptions? Imagine that you’re assigned the task of finding a specific book and then reading and explaining its contents to a class of students. The required sequence looks like the following:

  1. Get the specified book.
  2. Read aloud its contents.
  3. Explain the contents to a class of students.

But what happens if you can’t find the specified book? You can’t proceed with the rest of the actions without it, so you need ...

Get OCA Java SE 8 Programmer I Certification Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.