1

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?
zforgo
  • 2,508
  • 2
  • 14
  • 22
Surbhi Jain
  • 369
  • 1
  • 11
  • My opinion is that catching and re-throwing is not handling anything. One thing that might be acceptable would be wrapping a caught exception with a custom uncaught one, but I'm generally not in favor. – duffymo Apr 03 '23 at 11:40
  • That entirely depends on the specific situation, and whether having a more specific exception adds value. – Konrad Rudolph Apr 03 '23 at 11:40
  • @duffymo So you would rather a method threw an (imaginary) `LowLevelKernelException` than an `IOException` when the user unplugs the USB pendrive mid-access? I strongly disagree: failure to wrap exceptions leaks implementation details and should be frowned upon in the same way as failure to mark private methods `private`. – Konrad Rudolph Apr 03 '23 at 11:41
  • 1
    Fair point, @KonradRudolph. I said "generally not in favor", but that was not meant to be a blanket condemnation. – duffymo Apr 03 '23 at 11:45

1 Answers1

0

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.

tturbo
  • 680
  • 5
  • 16