We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Initially in catch block i simply wrote sysout(e); to print exception message.
But one of the test case failed for arithmetic exception so i used ternery operator like below instaed of writing catch block for all exceptions.
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 = 0;
int y = 0;
x = sc.nextInt();
y = sc.nextInt();
System.out.print(x/y);
}catch(Exception e){
String emsg = (e.getClass().getName().equalsIgnoreCase("java.lang.ArithmeticException")) ? "java.lang.ArithmeticException: / by zero" : e.getClass().getName();
System.out.print(emsg);
}
finally{
sc.close();
}
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Exception Handling (Try-catch)
You are viewing a single comment's thread. Return to all comments →
Initially in catch block i simply wrote sysout(e); to print exception message.
But one of the test case failed for arithmetic exception so i used ternery operator like below instaed of writing catch block for all exceptions.
public class Solution {
}