gpt4 book ai didi

方法定义中的 Java 异常

转载 作者:行者123 更新时间:2023-12-02 11:52:49 24 4
gpt4 key购买 nike

什么时候必须在方法定义中编写可抛出异常?

例如,我的构造函数可以同时使用:

public Test(int s, String t) {
if (s <= 0 || t == null) {
throw new IllegalArgumentException();
}
this.s = s;
this.t = t;
}

或者:

public Test(int s, String t) throws IllegalArgumentException {
if (s <= 0 || t == null) {
throw new IllegalArgumentException();
}
this.s = s;
this.t = t;
}

这个方法在没有它的情况下也可以工作:

public int mult(int n) {
if (n < 0) {
throw new IllegalArgumentException();
}
return n * this.s;
}

最佳答案

IllegalArgumentException 继承自RuntimeExceptionRuntimeException以及从它继承的所有类都是未经检查的异常,不必声明。请参阅RuntimeException的JavaDoc:

/**
* {@code RuntimeException} and its subclasses are <em>unchecked
* exceptions</em>. Unchecked exceptions do <em>not</em> need to be
* declared in a method or constructor's {@code throws} clause if they
* can be thrown by the execution of the method or constructor and
* propagate outside the method or constructor boundary.
*/

关于方法定义中的 Java 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47774167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com