Question

This question already has an answer here:

Note on the question: this is not a duplicate, Efficient try / catch block usage? was asked after this one. The other question is the duplicate.

I was wondering what was the best way to use try/catch. Is it better to limit the content of the try block to the minimum or to put everything in it?

Let me explain myself with an example:

Code 1:

try {
  thisThrowsAnException();
}
catch (Exception e) {
  e.printStackTrace();
}
thisDoesnt();

Code 2:

try {
  thisThrowsAnException();
  thisDoesnt();
}
catch (Exception e) {
  e.printStackTrace();
}

Assuming that thisThrowsAnException()... well... can throw an exception and thisDoesnt()... I'm sure you got it.

I know the difference between the two examples: in case the exception is caught, thisDoesnt() will be called in the first case, not in the second. As it doesn't matter for me, because the throwing of that exception would mean the application should stop, why would one use a version better than the other?

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top