Hi, I wonder if anyone can help. Basically, my question is are nested try / catch blocks valid / efficient / the best way to do things ?
Here's what I mean - I have a bit of code where I'm calling many methods that throw exceptions that I need to catch. So far, I've written the try / catch in a nested way - but it means that my code is massively indented, and the more code I add, the worse it gets ! For example:
I've tried writing the code in a linear fashion:
But that does not compile as s is not defined within the try/catch block of the s.getDatabase. I understand that, no problems.
So, back to the orginal question - are nested try/catch blocks the way to go ? or is there a better way ?
Nested exceptions IMHO are always bad - you get ugly, hard to read code. In your example, you catch the same exceptions twice. Why? The problem (to the rest of you app anyway) is the same - you can't acces the DB. Why not just wrap all that code in a try/catch block and log the exceptions?
Nested exceptions is not necessarily bad. It is like lots of other tools, if used correctly they can help you easily build some complicated stuff, but when in the hands of evil, they can bring an app down, and make it impossible to read and maintain.
Here's my look.
You would use nested Exceptions, and sometimes catching the same exception, if you want the outer code to continue running when an exception occurs in the inner code.
Second, I would also pull out the inner code into a seperate method that the outer code can call. This will stop the massive indentation, and achieve the same goals. Actually making the code more reusable and maintainable.
Here's an Example. I am actually going to make it two seperate posts, for the ability to compare. I am going to use some psuedocode.