publicvoidretrieveObjectById(Long id){try{ //..some code that throws SQLException}catch(SQLExceptionex){ //这里的异常打印仅仅是将错误堆栈输出到控制台,而在 Production 环境中,需要将错误堆栈输出到日志。ex.printStackTrace();}}
public void retrieveObjectById(Long id){
try{
//…抛出 IOException 的代码调用
//…抛出 SQLException 的代码调用
}catch(Exception e){
//这里利用基类 Exception 捕捉的所有潜在的异常,如果多个层次这样捕捉,会丢失原始异常的有效信息
throw new RuntimeException(“Exception in retieveObjectById”, e);
}
}
public void retrieveObjectById(Long id){
try{
//..some code that throws RuntimeException, IOException, SQLException
}catch(IOException e){
//仅仅捕捉 IOException
throw new RuntimeException(/*指定这里 IOException 对应的错误代码*/code,“Exception in retieveObjectById”, e);
}catch(SQLException e){
//仅仅捕捉 SQLException
throw new RuntimeException(/*指定这里 SQLException 对应的错误代码*/code,“Exception in retieveObjectById”, e);
}
}
public class A {
private static Logger logger = LoggerFactory.getLogger(A.class);
public void process() {
try {
B b = new B();
b.process();
//other code might cause exception
} catch (XXXException e) {
//如果 B 类 process 方法抛出异常,异常会在 B 类中被打印,在这里也会被打印,从而会打印 2 次
logger.error(e);
throw new RuntimeException(/* 错误代码 */ errorCode, /*异常信息*/msg, e);
}
}
}
public class B {
private static Logger logger = LoggerFactory.getLogger(B.class);
public void process() {
try {
//可能抛出异常的代码
} catch (XXXException e) {
logger.error(e);
throw new RuntimeException(/* 错误代码 */ errorCode, /*异常信息*/msg, e);
}
}
}
public void retieveObjectById(Long id){
try{
//..some code that throws SQLException
}catch(SQLException ex){
//将参数信息添加到异常信息中
throw new RuntimeException(“Exception in retieveObjectById with Object Id :”+ id, ex);
}
}