简体   繁体   中英

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. The exception is handled using try and catch

Class B -> calls the method from class A. It doesn't throw any exception now as the exception is handled in class A.

I wanted to know if I have to add throws and show that the exception is thrown in class B? Also, do I have to Unit test that the method called in class B throws exception? When I tried to do that, the test case failed.

Here is class A that handles the exception:

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:

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?

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. It's thrown/handled in Class A and it is not propagated to 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 . Then you could choose to handle it in Class B or propagate it further. 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.

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?

Class B doesn't throw the exception. It's thrown in Class A and handled over there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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