RAII
When using a stream, Closeable, or any class that uses RAII always properly close it with regard to exceptions.
To avoid having to manually do try...catch, try to use scoped guards such as unique_ptr or scoped_guard. Always try to follow RAII principles in classes you write by writing a proper constructor and destructor.
Use try...finally syntax.
EXAMPLE:
final BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()));
try{
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
}finally{
r.close();
}Or even better:
try(final BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()))){
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
}Last updated
Was this helpful?