面试题答案
一键面试自定义异常类
public class MyCustomException extends RuntimeException {
public MyCustomException(String message) {
super(message);
}
}
异常链使用场景
异常链通常在如下场景使用:
- 抽象层次转换:在底层代码捕获到一个具体的异常,但高层代码需要以更抽象的方式处理异常。例如,底层数据库操作抛出
SQLException
,而高层业务逻辑层更关心业务异常,此时可以将SQLException
包装在自定义的业务异常中抛出,这样高层代码无需了解具体的数据库异常细节。 - 隐藏敏感信息:底层异常可能包含敏感信息,如数据库用户名密码等。通过异常链,可以将底层异常包装在自定义异常中,在抛出时隐藏敏感信息。
异常链代码实现示例
public class ExceptionChainExample {
public static void main(String[] args) {
try {
performDatabaseOperation();
} catch (MyBusinessException e) {
e.printStackTrace();
}
}
private static void performDatabaseOperation() throws MyBusinessException {
try {
// 模拟数据库操作抛出SQLException
throw new java.sql.SQLException("Database operation failed");
} catch (SQLException e) {
// 将SQLException包装在自定义业务异常中抛出
throw new MyBusinessException("Business operation failed due to database issue", e);
}
}
}
class MyBusinessException extends RuntimeException {
public MyBusinessException(String message, Throwable cause) {
super(message, cause);
}
}