Reputation: 3069
BufferedReader in
= new BufferedReader(new FileReader(file));
try {
while((thisLine=in.readLine())!=null){
...
}
} catch (IOException e) {
//in.close();
// TODO Auto-generated catch block
e.printStackTrace();
}
in the code above, I want to close the read buffer in the catch block.But I find that the function in.close also throws an IOException. It look ugly if I nest another try-catch block in the catch block.So ,what is the correct way to deal with such a problem?
Upvotes: 1
Views: 49
Reputation: 41200
You can use finally
block for that. finally-block
execulated every time unless jvm exits abnormaly.
Java 7 try-with-resources
statement to automatically close, you need to close resouce stream explicitly,
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Example -
try(BufferedReader in
= new BufferedReader(new FileReader(file))){
while((thisLine=in.readLine())!=null){
...
}
}catch (IOException e) {
...
}
Upvotes: 2
Reputation: 121998
Do in finally block,Which is specially meant for cleanup.
From finally block docs
The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.
BufferedReader in
= new BufferedReader(new FileReader(file));
try {
while((thisLine=in.readLine())!=null){
...
}
} catch (IOException e) {
//in.close();
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
in.close
}
Upvotes: 1
Reputation: 13960
try {
in = new BufferedReader(new FileReader(file));
// stuff here
} finally {
try {
in.close()
} catch (IOException e) {} // ignore
}
Upvotes: 0
Reputation: 25950
Close the resources in a finally
block, not in a catch
block.
try
{
// actual code.
}
catch (IOException e) {
// handle exception
}
finally
{
try
{
in.close();
}
catch (IOException e) {
// handle exception
}
}
Upvotes: 1