简体   繁体   English

Java异常处理概念

[英]Java Exception Handling Concept

I had a confusion if I have to handle and test the exception for a class calling another class which handles the Exception. 如果我不得不为调用另一个处理异常的类的类处理和测试异常,我会感到困惑。

Here is a basic explanation for my classes: 这是我的课程的基本说明:

Class A -> Has a method and calls the method that throws exception. 类A->具有一个方法,并调用引发异常的方法。 The exception is handled using try and catch 使用try和catch处理异常

Class B -> calls the method from class A. It doesn't throw any exception now as the exception is handled in class A. 类B->从类A调用该方法。由于该异常是在类A中处理的,因此它现在不会引发任何异常。

I wanted to know if I have to add throws and show that the exception is thrown in class B? 我想知道是否必须添加引发并显示B类中引发了异常吗? Also, do I have to Unit test that the method called in class B throws exception? 另外,是否必须对B类中调用的方法引发异常进行单元测试? When I tried to do that, the test case failed. 当我尝试这样做时,测试用例失败了。

Here is class A that handles the exception: 这是处理异常的类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);
    }
}

Here is my class B: 这是我的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? 我想知道是否必须添加引发并显示B类中引发了异常吗?

If you mean the following: 如果您的意思是:

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

then the answer is no. 那么答案是否定的。 You don't have to declare that the method throws a SystemException , because it doesn't. 您不必声明该方法抛出SystemException ,因为它不会。 It's thrown/handled in Class A and it is not propagated to Class B . 它在Class A引发/处理,并且不会传播到Class B Did you, however, not handle the exception in Class A , you would have to specify your exception in the method signature of Class A if it's a Checked Exception . 但是,如果您没有处理Class A的异常,则如果它是Checked Exception则必须在Class A的方法签名中指定您的Checked Exception Then you could choose to handle it in Class B or propagate it further. 然后,您可以选择在Class B进行处理或进一步传播。 Also needing to specify that Class B throws a checked exception, or wrap in in a Runtime Exception and throw it without declaring it in the method signature. 还需要指定Class B抛出一个检查异常,或者包装一个Runtime Exception并抛出它,而不在方法签名中声明它。

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类中调用的方法引发异常进行单元测试?

Class B doesn't throw the exception. Class B不会引发异常。 It's thrown in Class A and handled over there. 它被扔到Class A并在那里处理。

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

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