Skip to content

Commit 2a49e54

Browse files
Merge pull request #127 from neelshah2409/master
Java Exception Handling(Try Catch) [hackerrank]
2 parents 8038a0b + a286423 commit 2a49e54

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*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)
2+
3+
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.
4+
5+
This problem will test your knowledge on try-catch block.
6+
7+
You will be given two integers and as input, you have to compute . If and are not bit signed integers or if is zero, exception will occur and you have to report it. Read sample Input/Output to know what to report in case of exceptions.
8+
*/
9+
10+
import java.io.*;
11+
import java.util.*;
12+
import java.text.*;
13+
import java.math.*;
14+
import java.util.regex.*;
15+
16+
public class Solution {
17+
18+
public static void main(String[] args) {
19+
20+
21+
Scanner scan = new Scanner(System.in);
22+
try {
23+
//taking 2 numbers inputs
24+
int x = scan.nextInt();
25+
int y = scan.nextInt();
26+
//dividing 2 numbers
27+
System.out.println(x / y);
28+
}
29+
catch(ArithmeticException | InputMismatchException e) {
30+
if (e instanceof ArithmeticException) {
31+
//if there is arithmetic exception occured in try block then it will be catched here
32+
System.out.println("java.lang.ArithmeticException: / by zero");
33+
} else if (e instanceof InputMismatchException){
34+
System.out.println("java.util.InputMismatchException");
35+
//if there is inputmismatch exception occured in try block then it will be catched here
36+
}
37+
}
38+
scan.close();
39+
}
40+
41+
42+
}

0 commit comments

Comments
 (0)