Class java.lang.Exception
Figure 525. 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) { System.err.println( "IO error"); } catch(FileNotFoundException e) { System.err.println("File not found"); } |
|
/* Translate {"one", "two", "three"} to {"first", "second", "third"}
* @param input The input String to be translated.
* @return See above explanation. */
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); } }
/**
* Translate {"one", "two", "three"} to {"first", "second", "third"}
* @param input The input String to be translated.
* @return See above explanation.
* @throws CardinalException If input not from list.
*/
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 }