0

Say, I have a function which can throw 3 types of exceptions e1, e2, and e3. So, in this function there are 2 ways of handling the exception. Which is the better way and why? Example:-

public void func() {

   block1 starts

   block1 ends
   e1 can thrown from block1

   block2 starts

   block2 ends
   e2 can thrown from block2

   block3 starts

   block3 ends
   e3 can thrown from block3
}

So, now I can handle the exceptions in 2 ways:- 1. Put 3 different try catch for 3 different blocks. 2. Put a single try on all 3 blocks and have 3 catch for each exception.

Which is considered a better way to do this?

3
  • 2
    consider to move every block to its own method, it looks like the method func is doing more than one thing! Commented Jun 27, 2017 at 7:26
  • then you can try-catch or throw those exceptions independently in its own method Commented Jun 27, 2017 at 7:27
  • @ΦXocę웃Пepeúpaツ Please edit your comment next time. Doesn't this question belong in codereview.stackexchange.com ? Commented Jun 27, 2017 at 7:28

3 Answers 3

1

It depends upon the effect of Exception.

  • If all exceptions are not affecting further processing then put your each exception point in separate try-catch block. So that if one exception is occurred then you can execute the line of codes which are not affected by this exception.
  • Put all the exceptions which are affecting further processing in a single try-catch block for better visibility and readability. Also by doing this you removes extra try-catch block. Other wise you will need to create nested try-catch block and much complex logic(because you have to stop further execution in this case).
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to handle each exception differently then go for multiple catch but if you want to catch the exception just for printing the stacktrace and continue the execution then go for catch with multiple exception.

Comments

0

Something like this would be the most flexible:

public void block1() throws e1 {
    try {
     ...
    } catch (e12) {
       throw new e1(e12);
    }
}

public void block2() throws e2 {
    similar to block1
}

public void block3() throws e3 {
    similar to block1
}

public void func() {
    try {
       block1();
       block2();
       block3();
    } catch (stuff) {
       stuff if you need it.
    }
}

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.