3. Catch or specify requirement

Java requires that a method either catch or specify all checked exceptions that can be thrown within the scope of the method.

3.1. Catch

A method can catch an exception by providing a method can catch an exception by providing an exception handler for that type of exception.

3.2. Specify

If a method chooses not to catch an exception, the method must specify that it can throw that exception.

3.3. Why Specify?

Because any exception that can be thrown by a method is really part of the method's public programming interface

3.4. Checked Exceptions

Checked exceptions are exceptions that are not runtime exceptions and are checked by the compiler.

3.5. Why not catch Runtime exceptions?

Runtime exceptions can occur anywhere in a program and in a typical program can be very numerous. Often the cost of checking for runtime exceptions exceeds the benefit of catching or specifying them.

3.6. Do not make all of your's exceptions Runtime

Do not throw a runtime exception or create a subclass of RuntimeException simply because you don't want to be bothered with specifying them.

3.7. Exceptions that can be thrown within the scope of the method

  • Exceptions that are thrown directly by the method with Java's throw statement;

  • Exceptions that are thrown indirectly by the method through calls to other methods.

Audio in Portuguese