-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExceptionHandling.java
78 lines (67 loc) · 1.95 KB
/
ExceptionHandling.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Object -> Throwable:
* Error: ThreadDeath / IOError / OutOfMemory
Errors can not be handled
* Exceptions: RuntimeException (Unchecked Exceptions) - SQLException (Checked Exception)
*/
import com.sun.security.jgss.GSSUtil;
// Custom exception
class RaedException extends Exception {
public RaedException(String string) {
super(string);
}
}
// This class can throw an ClassNotFoundException
class A {
void show() {
try {
Class.forName("myClass");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
public class ExceptionHandling {
public static void main(String[] a) {
A obj = new A();
obj.show();
/* Cascaded Exceptions */
// Arithmetic Exception
int i = 1;
int j = 0;
// Index out of bounds exception
int[] array = new int[5];
try {
j = 10/i;
System.out.println(array[1]);
System.out.println(array[4]);
}
catch(ArithmeticException e) {
System.out.println("Arithmetic exception");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Out of bound");
}
catch(Exception e) {
System.out.println(e);
}
/* Throwable */
// Throw ArithmeticException
int x = 20;
int y = 1;
try {
y = 18/2;
if(y == 0)
throw new ArithmeticException(y + " was divided by a number > " + y);
if(y == 1)
throw new RaedException(y + " was divided by itself");
}
catch (ArithmeticException e) {
j = 18/1;
System.out.println("J: " + j + "\n" + e);
}
catch (RaedException e) {
System.out.println(e);
}
}
}