Chapter 6 Exceptions and Assertions

THE OCP EXAM TOPICS COVERED IN THIS CHAPTER INCLUDE THE FOLLOWING:

  • ✓  Exceptions and Assertions
    • Use try-catch and throw statements
    • Use catch, multi-catch, and finally clauses
    • Use Autoclose resources with a try-with-resources statement
    • Create custom exceptions and Auto-closeable resources
    • Test invariants by using assertions

images

You have already learned the basics of exceptions for the OCA. While reviewing these basics, we will point out the additional exception classes that you are expected to know for the OCP. We will also cover the more advanced features introduced in Java 7 for working with exceptions. We will end the chapter by introducing assertions.

Reviewing Exceptions

A program can fail for just about any reason. Here are just a few of the possibilities for program failure that are commonly covered on the OCP exam:

  • Your program tries to read a file that doesn’t exist.
  • Your program tries to access a database, but the network connection to the database is unavailable.
  • You made a coding mistake and wrote an invalid SQL statement in your JDBC code.
  • You made a coding mistake and used the wrong format specifiers when using DateTimeFormatter.

As you can see, some of these are coding mistakes. Others are completely beyond your control. Your program can’t help it if the network connection goes down. What it can do is deal with the situation. ...

Get OCP Oracle® Certified Professional Java® SE 8 Programmer II 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.