首先:Java具有处理异常的内置机制。使用try语句,我们可以测试一段代码是否有错误。 catch块包含代码,该代码说明发生异常时该怎么做。
此问题将测试您对try-catch块的了解。
您将获得两个整数x,y并作为输入,您必须计算x / y。如果和不是位有符号整数或者如果为零,则会发生异常,您必须报告它。阅读示例输入/输出以了解在发生异常时要报告的内容。
我已经通过了除了一个测试用例以外的所有测试用例,当用户输入一个0时,它需要java.lang.ArithmeticException:/为零。我的catch输出System.out.println(“java.util.InputMismatchException”); 我怎样才能通过最后一个测试用例?
import java.io.*;
import java.util.*;
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. */
try{
Scanner scan = new Scanner(System.in);
int input1 = scan.nextInt();
int input2 = scan.nextInt();
scan.close();
System.out.println(divideInput(input1,input2));
}catch(Exception e){
System.out.println("java.util.InputMismatchException");
}
}
public static int divideInput(int input1, int input2)
{
int sum;
sum = input1 / input2;
return sum;
}
}
答案 0 :(得分:0)
让它运行并通过所有测试用例。
`import java.io.*;
import java.util.*;
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. */
try{
Scanner scan = new Scanner(System.in);
int input1 = scan.nextInt();
int input2 = scan.nextInt();
scan.close();
System.out.println(divideInput(input1,input2));
}
catch(ArithmeticException e){
System.out.println("java.lang.ArithmeticException: / by zero");
}
catch(InputMismatchException e){
System.out.println("java.util.InputMismatchException");
}
}
public static int divideInput(int input1, int input2)
{
int sum;
sum = input1 / input2;
return sum;
}
}`
答案 1 :(得分:0)
你可以像下面这样抓住它: -
//just use any one of these three statement
e.printStackTrace();
System.err.println(e.toString());
System.err.println(e.getMessage());