假设我有一个类,要求是“更改以下代码以在“den”为 0 时抛出已检查的异常,并更改函数以捕获该异常”。
public class divide {
void divide(int num, int den){
System.out.println(""+(num/den));
}
void fun(){
divide(4,2);
}
}
下面哪一个是抛出异常的正确方法?
选项 1:
void divide(int num, int den) throws Exception{
if(den==0){
throw new Exception("Dividebyzero");
}
System.out.println(""+(num/den));
}
void fun(){
try {
divide(4,2);
} catch (Exception e) {
}
}
选项 2://我认为这个是正确的
void divide(int num, int den){
if(den==0){
throw new RuntimeException("Dividebyzero");
}
System.out.println(""+(num/den));
}
void fun(){
try {
divide(4,2);
} catch (RuntimeException e) {
}
}
选项 3:
void divide(int num, int den) throws Exception{
if(den==0){
throw new RuntimeException;
}
System.out.println(""+(num/den));
}
void fun(){
try {
divide(4,2);
} catch (Exception, RuntimeException) {
}
}
这个问题来自一个 Java 练习。我已经学习 Java 好几年了,但我对 try catch throw 有点困惑。我个人认为选项 2 是正确的,因为我们只抛出一次异常,还是我错了?
最佳答案
Which of the following one is the correct way to throw exception?
我不会使代码复杂化,而是使用它已经抛出的异常。
void printDivide(int num, int den) throws ArithmeticException {
System.out.println(num / den);
}
使用不同的异常不仅更加复杂,而且令人困惑。
让我们设置它是一个不同的例子,然后 IllagelArgumentException 是非法参数的一个很好的选择,比如创建一个数组
void createArray(int size) {
if (size < 0)
throw IllegalArgumentException("Size must be non-negative " + size);
this.array = new int[size];
}
关于java - 在 Java 中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706553/