Surbhi Jain
Surbhi Jain

Reputation: 369

Try-Catch vs re throwing an exception?

I have a function fun1(), which calls fun2(), which might throw an Exception :

public <T> T fun1(final String abc) throws XYZException {
    try {

        fun2()

    } catch (final Exception e) {
        throw new XYZException();
    }
}

  1. If we are re-throwing the exception, does try catch make sense here?
  2. Should we add throws in the method definition line?

Upvotes: 1

Views: 86

Answers (1)

tturbo
tturbo

Reputation: 1166

Well, you converting a general Exception in the more specific one XYZException. If this is the aim, it can make sense. Especially if XYZException is a user defined exception that helps to narrow the error down.

On reason could be, that a other (more upper) error handler specifically catches the XYZException and handles it. While if it would have thrown the general Exception it does not know how to handle it.

public static void main(String[] args){
    try {
      fun1<Type>("String");
    } catch (final XYZException e) {
      //Recover to XYZException or do something else specific to XYZException 
    } catch (final Exception e) {
      // Log the error and end the program, as we don't know how to recover
    }

For Example: As fun1 is a generic function, if fun1<Type1>("..") throws an XYZException you could for example try again with fun1<Type2>(".."). Both, fun1 and fun2 do not know what Type2 would be so they can't recover on their own.

Upvotes: 0

Related Questions