【问题标题】:Throw exception in Java在 Java 中抛出异常
【发布时间】:2016-08-10 22:23:48
【问题描述】:

假设我有一个类,要求是“如果“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是正确的,因为我们只抛出了一次异常,还是我错了?

【问题讨论】:

  • 选项 3 无法编译,选项 1 或 2 差别不大
  • 请忽略小的语法错误,但请查看整体结构@cricket_007
  • 那么,您是在问要使用哪个 Exception 子类?
  • 问题是问哪一个是正确的? @cricket_007
  • 我认为选项 1 更正确。表示方法抛出异常允许您实际抛出一个

标签: java exception-handling try-catch throws


【解决方案1】:

以下哪个是抛出异常的正确方法?

我不会使代码复杂化,而是使用它已经抛出的异常。

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];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-23
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多