Develop code that handles multiple Exception types in a single catch block.
The candidate is expected to understand and analyze the use of the try-catch statement with multiple types of Exception
in the same catch
block.
Before proceeding, based on the following example, understand the execution of the main
method and what is presented on the console after its execution.
link:../../../src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Complete.java[role=include]
The previous code has a try-catch block that you probably already know. The new about this code is in the first catch
block, where multiple exceptions are thrown and caught at the same time.
Exception caught: java.lang.NullPointerException
-
Since Java 7, multiple exceptions can be caught in the same catch.
-
Only one variable is allowed for a
catch
block, and must be located at the end.src/org/j6toj8/languageenhancements/multipleexception/MultipleException_MultipleSameCatch.javalink:../../../src/org/j6toj8/languageenhancements/multipleexception/MultipleException_MultipleSameCatch.java[role=include]
-
It is not allowed to declare different exceptions, but would be redundant considering inheritance.
src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Redundant.javalink:../../../src/org/j6toj8/languageenhancements/multipleexception/MultipleException_Redundant.java[role=include]
-
When catching multiple Exceptions, it is not allowed to override the exception variable. But it’s possible if it’s just an
Exception
incatch
.src/org/j6toj8/languageenhancements/multipleexception/MultipleException_OverrideVar.javalink:../../../src/org/j6toj8/languageenhancements/multipleexception/MultipleException_OverrideVar.java[role=include]
-
As in previous releases, more generic types of
Exception
should come later, lower in the catch.src/org/j6toj8/languageenhancements/multipleexception/MultipleException_GenericsLower.javalink:../../../src/org/j6toj8/languageenhancements/multipleexception/MultipleException_GenericsLower.java[role=include]
-
As in previous versions, repeated exceptions are still prohibited.
src/org/j6toj8/languageenhancements/multipleexception/MultipleException_RepeatException.javalink:../../../src/org/j6toj8/languageenhancements/multipleexception/MultipleException_RepeatException.java[role=include]
-
As in previous versions, Checked Exceptions (those that inherit from
Exception
) can only be in acatch
if something intry
throws them.src/org/j6toj8/languageenhancements/multipleexception/MultipleException_CheckedException.javalink:../../../src/org/j6toj8/languageenhancements/multipleexception/MultipleException_CheckedException.java[role=include]
-
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 291). Wiley. Kindle Edition.
-
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking. Java Documentation.