Lecture notes |
Pdf slides |
|
NullPointerException
(NPE for short)
Lecture notes |
Pdf slides |
|
NullPointerException
is a class
Lecture notes |
Pdf slides |
|
(#1 of 4) |
NullPointerException
is a class
Lecture notes |
Pdf slides |
|
(#2 of 4) |
NullPointerException
is a class
Lecture notes |
Pdf slides |
|
(#3 of 4) |
NullPointerException
is a class
Lecture notes |
Pdf slides |
|
(#4 of 4) |
Lecture notes |
Pdf slides |
|
try {...} catch
{...}Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
try {...} catch {...} syntax
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 5) |
Lecture notes |
Pdf slides |
|
(#2 of 5) |
Lecture notes |
Pdf slides |
|
(#3 of 5) |
Lecture notes |
Pdf slides |
|
(#4 of 5) |
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
finally, no catchLecture notes |
Pdf slides |
|
try-with-resources (Java™ 7)
Lecture notes |
Pdf slides |
|
AutoCloseableLecture notes |
Pdf slides |
|
close() method in e.g.
class String
Lecture notes |
Pdf slides |
|
printStackTrace()Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
convertLecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
CardinalExceptionLecture notes |
Pdf slides |
|
CardinalExceptionLecture notes |
Pdf slides |
|
CardinalExceptionLecture notes |
Pdf slides |
|
final int public ❶ = 33; final String s = null; System.out.println(s.length())❷ ;
|
Compile time error: public is a Java™ keyword not to be used as variable's name. |
|
|
Run time error: De-referencing |
final String s = null;
System.out.println(s.length());Exception in thread "main" java.lang.NullPointerException at exceptionhandling.Npe.main(Npe.java:7)
...
if (somethingBadHappens) {
throw new NullPointerException();
}
...Without countermeasures your program will terminate
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 ...");Dear user, something bad just happened Business as usual ...
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]]
}]public static void main(String[] args) {
final Path
sourcePath = Paths.get("/tmp/test.txt"),
destPath = Paths.get("/tmp/copy.java");
// Compile time error:
// Unhandled exception:
java.io.IOException
Files.copy(sourcePath, destPath);
... |
public static void
main(String[] args) {
final String s = null;
// No problem
System.out.println(s.length()); |
@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 }
Scanner scanner = null; try { scanner = new Scanner(System.in); ... // Something may fail } finally { if (null != scanner) { scanner.close(); // Clean up, save resources! } }
try (final Scanner❶ scanner❷ = new Scanner(System.in)) { ... // Something may fail }❸ // implicitly calling scanner.close()
|
Class must implement interface |
|
|
Variable |
|
|
|
public class Scanner implements AutoCloseable ❶, ... { ... public void close() {...} ❷ } |
|
|
Promise to implement all methods being declared in |
|
|
Actually implementing a |
try (final String s = new String()) { // Error: Required type: AutoCloseable; Provided: String
...
}java.lang.Exception
|
Exception in thread "main" java.lang.NullPointerException at ex.Trace.c(Trace.java:10) at ex.Trace.b(Trace.java:7) at ex.Trace.a(Trace.java:6) at ex.Trace.main(Trace.java:4) |
try {
FileInputStream f = new FileInputStream(
new File("test.txt"));
}
catch(final FileNotFoundException e) {
System.err.println( "File not found");
}
catch (final IOException e) {
System.err.println( "IO error");
}
catch(final Exception e) {
System.err.println("General error");
} |
|
try {
FileInputStream f = new FileInputStream(
new File("test.txt"));
}
catch(Exception e) {
System.err.println("General error");
}
catch (IOException e) { // Already caught above!
System.err.println( "IO error");
}
catch(FileNotFoundException e) { // Already caught above!
System.err.println("File not found");
} |
|
/* Turn cardinals {"one", "two", "three"} into ordinals {"first", "second", "third"}
*
* @param input The cardinal to be translated.
* @return The corresponding ordinal or error message.
*/
static public String convert(final String input) {
switch (input) {
case "one": return "first";
case "two": return "second";
case "three": return "third";
default: return "no idea for " + input;
}
}Return false result, application continues.
Solution: Throw an exception. Steps:
Find a suitable exception base class.
Derive a corresponding exception class
Throw the exception accordingly.
Test correct behaviour.
Problem happens on wrong argument to
convert(...).
public class CardinalException extends IllegalArgumentException { public CardinalException(final String msg) { super(msg); } }
/* Turn cardinals {"one", "two", "three"} into ordinals {"first", "second", "third"}
*
* @param input The cardinal to be translated.
* @return The corresponding ordinal or error message.
*/
static public String convert(final String input)
throws CardinalException {
switch (input) {
case "one": return "first";
case "two": return "second";
case "three": return "third";
}
throw new CardinalException(
"Sorry, no translation for '" + input + "' on offer");
}@Test public void testRegular() { Assert.assertEquals("second", Cardinal.convert("two")); } @Test(expected = CardinalException.class) public void testException() { Cardinal.convert("four"); // No assert...() required }