Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Several try-catch blocks VS one big try-catch block [in a thread]

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.

like image 828
Vladislav Rastrusny Avatar asked Apr 27 '11 19:04

Vladislav Rastrusny


People also ask

Is it bad to have multiple try catch blocks?

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.

Can we use multiple catch block in single try block and how?

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.

Why we use multiple catch blocks?

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.

Is it good to have nested try catch?

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.


1 Answers

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.

like image 96
Milimetric Avatar answered Jan 04 '23 07:01

Milimetric