gpt4 book ai didi

Java异常处理概念

转载 作者:行者123 更新时间:2023-12-01 10:00:55 25 4
gpt4 key购买 nike

如果我必须处理和测试一个类调用另一个处理异常的类的异常,我会感到困惑。

这是我的类(class)的基本说明:

A类->有一个方法并调用抛出异常的方法。使用try和catch处理异常

B 类 -> 调用 A 类的方法。现在它不会抛出任何异常,因为异常是在 A 类中处理的。

我想知道是否必须添加 throws 并显示在 B 类中抛出异常?另外,我是否必须对 B 类中调用的方法抛出异常进行单元测试?当我尝试这样做时,测试用例失败了。

这是处理异常的 A 类:

public String getFooData(Foo foo, String foo1, String foo2) {
String foodata = "";
try {
FooRequest request = foo.setFoo1(foo1).setFoo2(foo2).buildQueryMessage();
foodata = request.getFooData();
} catch (SystemException e) {
errorReporter.report(".SystemException", e);
}
}

这是我的 B 类:

public String getFoo(String foo2) {
RequestBuilder requestBuilder = Request.Provider(ProviderType.foo);
String foodata = instanceOfA.getFooData(foo, foo1, foo2);
return foodata;
}

最佳答案

I wanted to know if I have to add throws and show that the exception is thrown in class B?

如果您的意思是以下内容:

public String getfoo(String foo2) throws SystemException { ... }

那么答案是否定的。您不必声明该方法抛出 SystemException,因为它不会。它在A 类 中抛出/处理,并且不会传播到B 类。但是,如果您没有处理 A 类 中的异常,则必须在 A 类 的方法签名中指定您的异常(如果它是 Checked Exception。然后您可以选择在B 类 中处理它或进一步传播它。还需要指定 B 类 抛出已检查异常,或者包装在 运行时异常 中并抛出它,而不在方法签名中声明它。

public String getfoodata(Foo foo, String foo1, String foo2) throws SystemException { ... }

Also, do I have to Unit test that the method called in class B throws exception?

B 类 不会引发异常。它被扔到 A 类 中并在那里进行处理。

关于Java异常处理概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816406/

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