hatellla
hatellla

Reputation: 5142

Better way to handle exception

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?

Upvotes: 0

Views: 74

Answers (3)

OldCurmudgeon
OldCurmudgeon

Reputation: 65879

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.
    }
}

Upvotes: 0

DDS
DDS

Reputation: 24

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.

Upvotes: 0

cse
cse

Reputation: 4104

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).

Upvotes: 1

Related Questions