简体   繁体   English

使用关键字throws来声明抛出运行时异常

[英]using keyword throws to declare throwing of Runtime Exceptions

For me, these code 对我来说,这些代码

static int faktorial (int n) throws ArithmeticException {
  if ((n < 0) || (n > 31)) { 
    throw new ArithmeticException();
  } 
  if (n > 1) {
    return n * faktorial(n - 1);
  } 
  else {
    return 1;
  }    
}

and the same code without 没有相同的代码

throws ArithmeticException

do the same, when I use it with the following code: 当我使用以下代码时,请执行相同的操作:

public static void main(String[] args) {
  try {
    int n;
    Scanner sc = new Scanner(System.in);  

    System.out.print("Insert integer number: ");        
    n = sc.nextInt();         
    System.out.println(n + "! = " + faktorial(n));
  }
  catch (InputMismatchException e) {
    System.out.println("Not an integer number!");
    e. printStackTrace();
  }
  catch (RuntimeException e) {
    System.out.println("Number is too big!");
    e. printStackTrace();
  }
}

Could someone describe me if use of 如果有人使用,可能有人形容我

    throws ArithmeticException

has some advantages in my code. 在我的代码中有一些优点。

I will also appreciate some good example of using keyword throws . 我还要了解一些使用关键字throws好例子。 Thank you very much! 非常感谢你!

Since ArithmeticException is an unchecked exception , listing it in the throws specification has no effect as far as the compiler is concerned. 由于ArithmeticException是一个未经检查的异常 ,因此在throws规范中列出它对编译器没有任何影响。

Nonetheless, I think it is a good idea to keep the throws specification for documentation purposes. 尽管如此,我认为保留throws规范以用于文档目的是一个好主意。

That said, ArithmeticException is probably not the right exception to be throwing when the function is called with an invalid argument. 也就是说,当使用无效参数调用函数时, ArithmeticException可能不是正确的异常。 Using IllegalArgumentException would be more appropriate. 使用IllegalArgumentException会更合适。

The above method signature uses the the expression throws ArithmeticException to tell the user of this function that method could throw this exception and they should be aware and catch it (if they want - "want" only because this exception is unchecked - and plan a workaround in that case). 上面的方法签名使用表达式throws ArithmeticException来告诉用户该函数该方法可能抛出此异常,并且他们应该知道并捕获它(如果他们想要 - “只需”因为未检查此异常 - 并计划一个变通方法在这种情况下)。

Except that ArithmeticException is not the proper exception to use in this case (you could technically use any one of them). 除非ArithmeticException不是在这种情况下使用的正确例外(您可以在技术上使用它们中的任何一个)。 A better exception to throw would be IllegalArgumentException since it implies the argument that was passed in was improper. 抛出的一个更好的例外是IllegalArgumentException因为它暗示传入的参数是不正确的。

Aside of what's beeing said, there is one upside that I find helping me code. 除了所说的内容之外,我发现有一个好处可以帮助我编写代码。

Eclipse can use that information (that the method is declared with throws RuntimeException ) and (on demand) add proper catch clause. Eclipse可以使用该信息(该方法使用throws RuntimeException声明)和(按需)添加适当的 catch子句。

Lets look at this: 让我们看看这个:

public static void main(String[] args) {
    test();
}

private static void test() {
    foo();
    bar();
    baz();
}

public static void foo() {

}

public static void bar() throws NullPointerException {

}

public static void baz() throws IllegalArgumentException {

}

adding try/ catch block inside method test will result in: 在方法test添加try/ catch block将导致:

private static void test() {
    try {
        foo();
        bar();
        baz();
    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

That's nice, isn't it? 那很好,不是吗? However, it works only with 1st level method invocation, so it does not pollute higher levels of abstraction with multiple catches of runtime exceptions: 但是,它仅适用于第一级方法调用,因此它不会因多次捕获运行时异常而污染更高级别的抽象:

public static void main(String[] args) {
    try {
        test();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private static void test() {
    foo();
    bar();
    baz();
}

That's nice as well. 那也很好。

Anyway, seeing that throws in javadoc is probably much more important :) 无论如何,看到javadoc中的抛出可能更重要:)

void Test.baz() throws IllegalArgumentException

Since Java does not provide a simple True/False flag to determine whether a given exception is checked or unchecked , you need to be aware of what types of exceptions you (as programmer) has to deal with (either catch or re-throw) and which you can chose not to handle (effectively ignore). 由于Java没有提供简单的True / False标志来确定是否检查了给定的异常,因此您需要了解您(作为程序员)必须处理的异常类型(捕获或重新抛出)和您可以选择不处理(有效忽略)。

In particular, the entire RunTimeException class is unchecked, and ArithmeticException is its sub-class. 特别是,取消选中整个RunTimeException类, ArithmeticException是其子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM