gpt4 book ai didi

java - 未处理的异常 - throws 不起作用

转载 作者:行者123 更新时间:2023-11-29 08:35:20 27 4
gpt4 key购买 nike

在测试用例中,我有一行

ZahlPasstNicht zahlPasstNicht = new ZahlPasstNicht(min, max, ist);

第二部分用红色下划线表示:Unhandled Exception: ZahlPassNicht

我可以使用 try/catch 或让构造函数抛出错误,我尝试了后者:

public class ZahlPasstNicht extends IndexOutOfBoundsException {
int a;
int b;
int c;

public ZahlPasstNicht(int a, int b, int c) throws ZahlPasstNicht {
this.a = a;
this.b = b;
this.c = c;
}

我做错了什么?

最佳答案

我想不出在任何情况下在异常类的构造函数中放置一个 throws 子句是有意义的,因为异常类在实例化时不应该抛出另一个异常(尤其是它本身)。

随便写

public ZahlPasstNicht(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}

如果您不打算抛出异常类,通常不会实例化它。

这没有多大意义:

ZahlPasstNicht zahlPasstNicht = new ZahlPasstNicht(min, max, ist);

这样做:

throw new ZahlPasstNicht(min, max, ist);

关于java - 未处理的异常 - throws 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44525602/

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