|
| 1 | +package exceptionsAndAssertions; |
| 2 | + |
| 3 | +/** |
| 4 | + * |
| 5 | + * @author chengfeili |
| 6 | + * Jun 10, 2017 10:57:52 AM |
| 7 | + * |
| 8 | + */ |
| 9 | +class checked extends Exception{ |
| 10 | + |
| 11 | +} |
| 12 | +public class CallingMethodsThatThrowExceptions { |
| 13 | + // checked is a checked exception. |
| 14 | + // it must be handled or declared. |
| 15 | + |
| 16 | + // method1: declare exception |
| 17 | + /* |
| 18 | + * public static void main(String[] args) throws checked { |
| 19 | + eat(); |
| 20 | + }*/ |
| 21 | + |
| 22 | + // method2: handle exception |
| 23 | + public static void main(String[] args) { |
| 24 | + try { |
| 25 | + eat(); |
| 26 | + } catch (checked e) { |
| 27 | + System.out.println("handle"); |
| 28 | + } |
| 29 | + |
| 30 | + // print an exception |
| 31 | + try { |
| 32 | + hop(); |
| 33 | + } catch (Exception e) { |
| 34 | + System.out.println(e); |
| 35 | + System.out.println(e.getMessage()); |
| 36 | + e.printStackTrace(); |
| 37 | + /* |
| 38 | + * java.lang.RuntimeException: cannot hop |
| 39 | + * cannot hop |
| 40 | + * java.lang.RuntimeException: cannot hop |
| 41 | + * at trycatch.Handling.hop(Handling.java:15) |
| 42 | + * at trycatch.Handling.main(Handling.java:7) |
| 43 | + */ |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private static void hop() { |
| 48 | + throw new RuntimeException("cannot hop"); |
| 49 | + } |
| 50 | + |
| 51 | + private static void eat() throws checked { |
| 52 | + |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + public void bad() { |
| 57 | + try { |
| 58 | + eatCarrot(); |
| 59 | + } catch (checked e) { // DOES NOT COMPILE |
| 60 | + System.out.print("sad rabbit"); |
| 61 | + } |
| 62 | + } |
| 63 | + */ |
| 64 | + |
| 65 | + public void good() throws checked { |
| 66 | + eatCarrot(); |
| 67 | + } |
| 68 | + |
| 69 | + private static void eatCarrot() { |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Java knows that eatCarrot() can’t throw a checked exception—which means |
| 74 | + * there’s no way for the catch block in bad() to be reached. In comparison, |
| 75 | + * good() is free to declare other exceptions. |
| 76 | + */ |
| 77 | + |
| 78 | + // subclasses |
| 79 | + /** |
| 80 | + * When a class overrides a method from a superclass or implements a method |
| 81 | + * from an interface, it’s not allowed to add new checked exceptions to the |
| 82 | + * method signature |
| 83 | + * |
| 84 | + * A subclass is allowed to declare fewer exceptions than the superclass or |
| 85 | + * interface. This is legal because callers are already handling them. |
| 86 | + * |
| 87 | + * declare new runtime exceptions in a subclass method is that the |
| 88 | + * declaration is redundant. Methods are free to throw any runtime |
| 89 | + * exceptions they want without mentioning them in the method declaration. |
| 90 | + */ |
| 91 | + |
| 92 | +} |
0 commit comments