Considering you have code like this:
doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing the same kind of exceptions.
Now I know, there is in fact a performance hit when constructing the exception, specifically unwinding the stack. And I have also read several articles pointing to a slight performance hit when entering try/catch blocks, but none of the articles seem to conclude anything.
My question is, is it recommended to keep the lines inside the try catch to bare minimum?, i.e. ONLY have inside the try clause the lines that can actually throw the exception you are catching. Does the code inside the try clause run slower or cause any performance hit?.
But more important what it is the best practice/more readable solution considering doing this:
try {
doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing the same kind of exceptions.
}
catch (MyCheckedException e) {
//handle it
}
or :
try {
doSomething() // this method may throw a checked a exception
}
catch (MyCheckedException e) {
//Store my exception in a Map (this is all running in a loop and I want it to continue running, but I also want to know which loops didn't complete and why)
continue;
}
//do some assignements calculations
try {
doAnotherThing() // this method may throw a checked a exception
}
catch (MyCheckedException e) {
//Store my exception in a Map (this is all running in a loop and I want it to continue running, but I also want to know which loops didn't complete and why)
continue;
}
This is considering that you will handle ALL this checked exceptions exactly the same way of course.
doSomething()
throws an exception. The assignments/calculations that follow will never execute. In the second example, they will execute because the exception thrown bydoSomething()
is handled before the assignments/calculations. Consider if it makes sense to execute the assignments/calculations ifdoSomething()
throws an exception. Will the results of the calculations still be correct? – FrustratedWithFormsDesignerthrow;
statement or something. The content is left as an exercise to the reader, I guess! – André Caron