-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCustomExceptDemo.java
More file actions
44 lines (38 loc) · 1.09 KB
/
Copy pathCustomExceptDemo.java
File metadata and controls
44 lines (38 loc) · 1.09 KB
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
// Use a custom exception.
// Create an exception.
class NonIntResultException extends Exception {
int n;
int d;
NonIntResultException(int i, int j) {
n = i;
d = j;
}
public String toString() {
return "Result of " + n + " / " + d + " is non-integer.";
}
}
class CustomExceptDemo {
public static void main(String args[]) {
// Here, numer is longer than denom.
int numer[] = { 4, 8, 15, 32, 64, 127, 256, 512 };
int denom[] = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.length; i++) {
try {
if((numer[i]%2) != 0)
throw new NonIntResultException(numer[i], denom[i]);
System.out.println(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]);
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
}
catch (NonIntResultException exc) {
System.out.println(exc);
}
}
}
}