Skip to content
Snippets Groups Projects
Commit 50b15270 authored by Goik Martin's avatar Goik Martin
Browse files

Checked vs unchecked exceptions

parent ea4a25bd
No related branches found
No related tags found
No related merge requests found
This diff is collapsed.
This diff is collapsed.
......@@ -2,6 +2,7 @@
<chapter annotations="slide" version="5.1" xml:id="sw1ChapterErrorHandling"
xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xila="http://www.w3.org/2001/XInclude/local-attributes"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:ns="http://docbook.org/ns/transclusion"
......@@ -40,14 +41,253 @@ System.out.println(s.length())<co linkends="sd1_fig_compileRuntime-2"
</calloutlist>
</figure>
<figure xml:id="sd1FigExceptionBasics">
<title>Basics on exception handling</title>
<figure xml:id="sd1_fig_npe">
<title><classname
xlink:href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html">NullPointerException</classname>
(<acronym>NPE</acronym> for short)</title>
<programlisting language="java">final String s = null;
System.out.println(s.length());</programlisting>
<screen>Exception in thread "main" java.lang.NullPointerException
at exceptionhandling.Npe.main(Npe.java:7)</screen>
</figure>
<figure xml:id="sd1_fig_npe_is_a_class">
<title><classname
xlink:href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html">NullPointerException</classname>
is a class</title>
<mediaobject>
<imageobject>
<imagedata fileref="Ref/ErrorHandling/exception.multi.svg"/>
<imagedata fileref="Ref/ErrorHandling/npe.multi.svg"/>
</imageobject>
</mediaobject>
</figure>
<figure xml:id="sd1_fig_exceptionsAreBeingThrown">
<title>Throwing an exception</title>
<programlisting language="java">...
if (somethingBadHappens) {
throw new NullPointerException();
}
...</programlisting>
<note>
<para>Without countermeasures your program will terminate</para>
</note>
</figure>
<figure xml:id="sd1_fig_npeErrorMessage">
<title>Catching an exception by <code language="java">try {...} catch
{...}</code></title>
<programlisting language="java">final String s = null;
try {
System.out.println(s.length()) ;
} catch (final NullPointerException e) {
System.out.println("Dear user, something bad just happened");
}
System.out.println("Business as usual ...");</programlisting>
<screen>Dear user, something bad just happened
Business as usual ...</screen>
</figure>
<qandaset defaultlabel="qanda"
xml:id="sd1_errorhandling_qanda_CatchingWrongException">
<title>Mind your prey</title>
<qandadiv>
<qandaentry>
<question>
<para>We reconsider:</para>
<programlisting language="java">final String s = null;
try {
System.out.println(s.length()) ;
} catch (final NullPointerException e) {
System.out.println("Dear user, something bad just happened");
}
System.out.println("Business as usual ...");</programlisting>
<para>What happens if <classname
xlink:href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html">NullPointerException</classname>
is being replaced by <classname
xlink:href="https://docs.oracle.com/javase/9/docs/api/java/lang/OutOfMemoryError.html">OutOfMemoryError</classname>?</para>
<para>Is there a way to catch all possible exceptions?</para>
</question>
<answer>
<para>We have:</para>
<programlisting language="java">final String s = null;
try {
System.out.println(s.length()) ;
} catch (final OutOfMemoryError e) {
System.out.println("Dear user, something bad just happened");
}
System.out.println("Business as usual ...");</programlisting>
<para>The runtime system throws a <classname
xlink:href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html">NullPointerException</classname>
which is no subclass of <classname
xlink:href="https://docs.oracle.com/javase/9/docs/api/java/lang/OutOfMemoryError.html">OutOfMemoryError</classname>:</para>
<mediaobject>
<imageobject>
<imagedata fileref="Ref/ErrorHandling/qandaNpeMemory.svg"/>
</imageobject>
</mediaobject>
<para>If <classname
xlink:href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html">NullPointerException</classname>
was a subclass of <classname
xlink:href="https://docs.oracle.com/javase/9/docs/api/java/lang/OutOfMemoryError.html">OutOfMemoryError</classname>
it would still be caught. But lacking an (upcast) inheritance
relationship we are being left with the runtimes default
terminating behaviour:</para>
<screen>Exception in thread "main" java.lang.NullPointerException
at exceptionhandling.NpeMsg.main(NpeMsg.java:8)</screen>
</answer>
</qandaentry>
</qandadiv>
</qandaset>
<figure xml:id="sd1_fig_tryCatchSyntax">
<title><code language="java">try {...} catch {...}</code> syntax</title>
<programlisting language="java">try {
[code that may throw an exception]
}[catch (ExceptionType-1 e) {
[code that is executed when ExceptionType-1 is thrown]
}] [catch (ExceptionType-2 e) {
[code that is executed when ExceptionType-2 is thrown]
}]
...
} [catch (ExceptionType-n e) {
[code that is executed when ExceptionType-n is thrown]
}]
[finally {
[code that runs regardless of whether an exception was thrown]]
}]</programlisting>
</figure>
<section xml:id="sd1_errorhandling_sect_checkedVsUnchecked">
<title>Checked vs unchecked exceptions</title>
<figure xml:id="sd1_errorhandling_fig_checkedVsUnchecked">
<title>Checked and unchecked exceptions</title>
<informaltable border="0">
<tr>
<td valign="top"><programlisting language="none">public static void main(String[] args) {
final Path
sourcePath = Paths.get("/tmp/test.txt"),
destPath = Paths.get("/tmp/copy.java");
// Compile time error:
// <emphasis role="red">Unhandled exception:
java.io.IOException</emphasis>
Files.copy(sourcePath, destPath);
...</programlisting></td>
<td valign="top"><programlisting language="none">public static void
main(String[] args) {
final String s = null;
// <emphasis role="red">No problem</emphasis>
System.out.println(s.length()); </programlisting></td>
</tr>
</informaltable>
</figure>
<figure xml:id="sd1FigExceptionBasics">
<title>Checked and unchecked exceptions</title>
<mediaobject>
<imageobject>
<imagedata fileref="Ref/ErrorHandling/exception.multi.svg"/>
</imageobject>
</mediaobject>
</figure>
</section>
<section xml:id="sd1_errorhandling_exceptionsAndJunit">
<title>Exceptions and <xref linkend="glo_Junit"/></title>
<figure xml:id="sd1_fig_junitExpectedException">
<title>Expected exceptions in <xref linkend="glo_Junit"/></title>
<programlisting language="java">@Test(expected = FileAlreadyExistsException.class)
public void copyFile() throws IOException {
final Path
source = Paths.get("/tmp/source.txt"),
dest = Paths.get("/tmp/dest.txt");
Files.copy(source, dest); // May work.
Files.copy(source, dest); // Failure: FileAlreadyExistsException
}</programlisting>
</figure>
<qandaset defaultlabel="qanda"
xml:id="sd1_errorhandling_qanda_junitExpectedException">
<title>Expected exception test failure</title>
<qandadiv>
<qandaentry>
<question>
<para>We reconsider:</para>
<programlisting language="java">@Test(expected = FileAlreadyExistsException.class)
public void copyFile() throws IOException {
final Path
source = Paths.get("/tmp/source.txt"),
dest = Paths.get("/tmp/dest.txt");
Files.copy(source, dest); // May work.
Files.copy(source, dest); // Failure: FileAlreadyExistsException
}</programlisting>
<para>Modify this code by catching the exception inside
<methodname>copyFile()</methodname> using <code
language="java">try {...} catch {...}</code>. Then execute the
test. What do you observe?</para>
</question>
<answer>
<para>We catch the exception in question:</para>
<programlisting language="java">@Test(expected = FileAlreadyExistsException.class)
public void copyFile() throws IOException {
final Path
source = Paths.get("/tmp/source.txt"),
dest = Paths.get("/tmp/dest.txt");
try {
Files.copy(source, dest); // May work.
Files.copy(source, dest); // Failure: FileAlreadyExistsException
} catch (final FileAlreadyExistsException e) {
System.out.println("Destination file already exists");
}
}</programlisting>
<para>Since we swallow the <classname
xlink:href="https://docs.oracle.com/javase/9/docs/api/java/nio/file/FileAlreadyExistsException.html">FileAlreadyExistsException</classname>
ourselves it is no longer being thrown. Due to the
<code>@Test(expected = FileAlreadyExistsException.class)</code>
annotation test execution now fails:</para>
<screen>Destination file already exists
java.lang.AssertionError: Expected exception: java.nio.file.FileAlreadyExistsException</screen>
</answer>
</qandaentry>
</qandadiv>
</qandaset>
</section>
</section>
</chapter>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment