0

I read one piece of codes:

public void myfunc() throws MyException {
       try {
            // codes here
        } catch(AlreadyExistsException e) {
            throw new sub1MyException("yyy"); // first catch block
        } catch(Exception e) {
            throw new sub2MyException("xxx"); // second catch block
        }
}

sub1MyException and sub2MyException are both sub-classes of MyException. AlreadyExistsException is NOT sub-class of MyException.

I have some questons:

1, will throw new sub1MyException("yyy"); be caught by the second catch block?

2, Any anti-patterns in the above codes. I did some search but did not find any similar patterns or examples. If any, please leave a comment.

3, I think, it is not necessary to use so many sub-classes because exception messages already in the Exception. Custom messages such as yyy and xxx not very helpful.

Thanks

2
  • 1. is easy to test / 2. I would say no / 3. it's better not to rely on messages. I mean new SomeException("error 1") and for something else new SomeException("error 2") is most of the time a bad idea Commented Nov 17, 2017 at 16:23
  • Related: stackoverflow.com/questions/4566450/… Commented Nov 17, 2017 at 16:27

2 Answers 2

0
  1. No, you'd have to nest a try-catch block inside your catch for that to happen.
  2. Catching Exception is an anti-pattern in itself, but it's so widely used that people don't really care anymore. You shouldn't really catch Exception because then you basically have no idea what you are expecting (and try-catch blocks are about predictability). The only place in which you should blanket-catch Exception is in a general error handler that handles the final error dispatch (showing a big ugly error message, logging errors etc.)
  3. If the only thing in which your errors differ is in the error message, then no, there's no use in differentiating them. If there's a difference in how they propagate (for example, one is a recoverable error and the other is a runtime error), then you should differentiate. The rule of the thumb is that you should only have different Exception classes if they differ in their propagation strategy (i.e. in which try-catch blocks they are handled in further down the road).
Sign up to request clarification or add additional context in comments.

Comments

0

1) no it won't. it's not inside the try-catch.

2 & 3 - it depends what you need to do. if you need to handle the different exceptions in a different manner, then do so. Otherwise you can just catch Exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.