Class java.lang.Exception
Figure 531. Method
printStackTrace() |
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 }
