forked from builder-of-web3/HackR_Java_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathException handling
More file actions
63 lines (47 loc) · 1.74 KB
/
Exception handling
File metadata and controls
63 lines (47 loc) · 1.74 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution. (Wikipedia)
Java has built-in mechanism to handle exceptions. Using the try statement we can test a block of code for errors. The catch block contains the code that says what to do if exception occurs.
This problem will test your knowledge on try-catch block.
You will be given two integers xx and yy as input, you have to compute x/y. If x and y are not 32 bit signed integers or if y is zero, exception will occur and you have to report it. Read sample Input/Output to know what to report in case of exceptions.
Sample Input 1:
10
3
Sample Output 1:
3
Sample Input 2:
10
Hello
Sample Output 2:
java.util.InputMismatchException
Sample Input 3:
10
0
Sample Output 3:
java.lang.ArithmeticException: / by zero
Sample Input 4:
23.323
0
Sample Output 4:
java.util.InputMismatchException
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
try{
int x = sc.nextInt();
int y = sc.nextInt();
if(y == 0)
throw new ArithmeticException("/ by zero");
System.out.print(x/y);
} catch(InputMismatchException ime){
System.out.print("java.util.InputMismatchException");
}
catch(ArithmeticException ae){
System.out.print(ae);
}
}
}