|
| 1 | +packagesporadic.exceptionsCanBeSelfDefined; |
| 2 | + |
| 3 | +/** |
| 4 | + * This is a simple program to help myself better understand what it really |
| 5 | + * means to catch/throw an exception. |
| 6 | + * |
| 7 | + * "catch" means to catch the possible exception while executing that method, if |
| 8 | + * the potential exception is not caught in time, the calling method will be |
| 9 | + * interrupted, and all the calling trace up to the main method will be |
| 10 | + * interrupted subsequently, then the whole program is interrupted/stopped. |
| 11 | + * |
| 12 | + * But with catch statement, the possible exception is caught, or in other |
| 13 | + * words, the exception is being handled/taken care of. Thus the calling method |
| 14 | + * and the whole program could continue. Cool! p.s. swallow the exception just |
| 15 | + * means not to catch it. |
| 16 | + * |
| 17 | + * This "catch" block can be kind of equivalent to "throws" statement in the |
| 18 | + * method definition/declaration, I can do either one, It's just that "throws" |
| 19 | + * cannot catch that exception, but it lets the compiler be aware that it's |
| 20 | + * possible that this method will throw an exception. |
| 21 | + * |
| 22 | + * However, with a "throw" statement, I throw this caught exception back to the |
| 23 | + * running program, this way, the program will be interrupted/stopped again! |
| 24 | + */ |
| 25 | + |
| 26 | +publicclassUnderstandExceptionTryCatch { |
| 27 | + |
| 28 | +privatestaticvoiddivide(inta,intb) { |
| 29 | +try { |
| 30 | +System.out.println(a /b); |
| 31 | +}catch (ArithmeticExceptionae) { |
| 32 | +System.out.println("It enters ArithmeticException branch."); |
| 33 | +ae.printStackTrace(); |
| 34 | +// throw ae; |
| 35 | +}catch (RuntimeExceptionre) { |
| 36 | +System.out.println("It enters RuntimeException branch."); |
| 37 | +re.printStackTrace(); |
| 38 | +// throw re; |
| 39 | +}catch (Exceptione) { |
| 40 | +System.out.println("It enters Exception branch."); |
| 41 | +e.printStackTrace(); |
| 42 | +// throw e; |
| 43 | +}catch (Throwablet) { |
| 44 | +System.out.println("It enters Throwable branch."); |
| 45 | +t.printStackTrace(); |
| 46 | +// throw t; |
| 47 | +} |
| 48 | +} |
| 49 | + |
| 50 | +publicstaticvoidmain(String[]args) { |
| 51 | +divide(2,0); |
| 52 | +System.out.println("That's the end of the program!"); |
| 53 | +} |
| 54 | +} |