I've found one recommendation, that says, that we should try to keep one try/except statement per thread.
I have a class, that implements Runnable (Java, but it doesn't actually matter). It has several blocks in it each one surrounded in it's own try-catch block with logging and handling. Each block throws same exception class.
Do you think I should widen exception collection creating an exception per each operation, put all blocks under one try-catch block and handle each one differently? Some example of what I have is here.
Thanks in advance.
You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.
Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.
Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency. The bytecode generated while compiling this program will be smaller than the program having multiple catch blocks as there is no code redundancy.
Nesting try-catch blocks severely impacts the readability of source code because it makes it to difficult to understand which block will catch which exception.
The example you posted suggests having a single catch block for clarity and maintainability. I agree with that, it's good advice. Are you worried about performance? Theoretically, if you're doing stuff between your exception throwing blocks, multiple try/catch blocks would be faster. But the difference would be quite small, and maintainability would suffer. Go with the single try catch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With