我以这种方式编写了代码,其中方法除法在除以两个整数后返回 double 值。如果我不包含 try catch block ,它可以正常工作。但是当我将带有类型转换的整数除法包含在 try block 内时,如图所示下面,它导致编译问题...请解决我的问题。
import java.util.Scanner;
class Division {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Division div=new Division();
System.out.println("Enter the two numbers to perform division operation:");
int x=sc.nextInt();
int y=sc.nextInt();
div.division(x,y);
}
public double division(int x,int y){
try{
double z=(double)(x/y);
return z;
}
catch(ArithmeticException ae){
ae.printStackTrace();
}
}
}
最佳答案
您的除法函数中缺少返回值。通过捕获异常,您表示您将在出现问题时采取一些措施来处理它,并且之后执行将继续。
最好在这里抛出异常,因为如果除以零,将不会返回任何内容。或者你可以返回一些无意义的东西,比如 -1
public double division(int x,int y){
try{
double z=(double)(x/y);
return z;
}
catch(ArithmeticException ae){
ae.printStackTrace();
}
return -1;
}
更好的解决方案是,如果除数为 0,则抛出异常,然后在使用它的地方进行处理
public double division(int x, int y) throws ArithmeticException {
if (y == 0)
throw new ArithmeticException("Cannot divide by 0");
double z = (double) (x / y);
return z;
}
关于java - 为什么当我尝试在 try block 内进行类型转换时,我的 java 代码会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706492/