在Finally块中清理资源或者使用try-with-resource语句
public void automaticallyCloseResource (){
File file = new File ("./tmp.txt" );
try (FileInputStream is = new FileInputStream (file );){
is .read ();
}catch (FileNotFoundException e ){
log .error (e );
}catch (IOException e ){
log .error (e );
}
}
//这种使用毫无意义
public void doNotDoThis () throws Exception {}
//指定具体的异常
public void doThis () throws NumberFormatException {}
/**
* This method does something extremely useful...
*
* @param input
* @throws MyBussinessException if ... happens
*/
public void doSomething (String input ) throws MyBussinessException {}
try {
new Long ("xyz" );
}catch (NumberFormatException e ){
log .error (e );
}
public void catchMostSpecificExceptionFirst (){
try {
doSomething ("A message" );
}catch (NumberFormatException e ){
log .error (e );
}catch (IllegalArgumentException e ){
log .error (e );
}
}
public void doNotCatchThrowable (){
try {
}catch (Throwable t ){
//never do this
}
}
public void doNotIgnoreExceptions (){
try {
}catch (NumberFormatException e ){
log .error ("This should never happen :" + e );
}
}
try {
new Long ("xyz" );
}catch (NumberFormatException e ){
log .error (e );
//throw e; //do not do this
}
public void wrapException (String input ) throws MyBusinessException {
try {
}catch (NumberFormatException e ){
throw new MyBusinessException ("A message that describes the error." ,e );
}
}