// exceptions/Human.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Catching exception hierarchies
class Annoyance extends Exception {}
class Sneeze extends Annoyance {}
public class Human {
public static void main(String[] args) {
// Catch the exact type:
try {
throw new Sneeze();
} catch (Sneeze s) {
System.out.println("Caught Sneeze");
} catch (Annoyance a) { // warning: unreachable catch clause
System.out.println("Caught Annoyance");
}
// Catch the base type:
try {
throw new Sneeze();
} catch (Annoyance a) {
System.out.println("Caught Annoyance");
}
// try {
// throw new Sneeze();
// } catch (Annoyance a) {
// System.out.println("Caught Annoyance");
// } catch (Sneeze s) { // Compile error
// System.out.println("Caught Sneeze");
// }
}
}
/* Output:
Caught Sneeze
Caught Annoyance
*/
One important guideline in exception handling: Don't catch an exception unless we know what to do with it.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/exceptions/Human.java