// 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
本文通过一个具体的Java代码示例,深入探讨了异常处理的最佳实践,强调了只捕获我们知道如何处理的异常的重要性。代码展示了不同类型的异常如何被捕获,并解释了异常层次结构的概念。
763

被折叠的 条评论
为什么被折叠?



