Is there a "best practice" for how much code to put inside a try/catch
block?
I have posted 3 different scenarios below.
I did not include behavior in each catch
block and i did not include the finally block. This was to improve readability for viewers. Assume each catch
does something differently. And assume the finally
will be closing the stream. Just trying to create an easy to read example for future readers.
- Control, no
try/catch
. - Code with 1
try/catch
for each place needed. - Code with only 1
try/catch
surrounding whole code block.
What is generally accepted as the best practice and why?
Scenario 1
Code without try/catch
, just for control.
BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"));
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
bufferedReader.close();
Scenario 2
Code with a try/catch
block for each individual place needed.
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("somepath"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
Scenario 3
Code with 1 try/catch
surrounding the whole block of code.
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"));
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}