Skip to content

Commit 3aac1c3

Browse files
[RandomJava] add catch exception example
1 parent 2489551 commit 3aac1c3

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package catchExceptions;
2+
3+
/**This program shows that if the inner catch block:
4+
* catch (ArithmeticException ae)
5+
* cannot catch the exception, in this case, it's RuntimeException, it'll be caught by the outer catch:
6+
* catch (Exception e)
7+
* although the exception is being thrown from the inner try block.
8+
* */
9+
public class CatchException {
10+
private static void throwExceptionMethod(int a, int b) {
11+
try {
12+
//do something here..
13+
int c = a + b;
14+
System.out.println("c is " + c );
15+
16+
try {
17+
System.out.println(a / b);
18+
throw new RuntimeException("a random exception");
19+
} catch (ArithmeticException ae) {
20+
System.out.println("It enters ArithmeticException branch.");
21+
ae.printStackTrace();
22+
// throw ae;
23+
}
24+
} catch (Exception e) {
25+
System.out.println("It enters Exception branch: " + e.getMessage());
26+
e.printStackTrace();
27+
// throw e;
28+
}
29+
}
30+
31+
public static void main(String[] args) {
32+
throwExceptionMethod(2, 4);
33+
System.out.println("That's the end of the program!");
34+
}
35+
}

0 commit comments

Comments
 (0)