Reputation: 5142
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
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
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
Reputation: 4104
It depends upon the effect of Exception
.
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.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