面试题答案
一键面试异常处理架构设计
- 自定义异常类:根据业务场景,定义不同类型的自定义异常类,继承自
Exception
或RuntimeException
。例如:
public class BusinessException extends Exception {
public BusinessException(String message) {
super(message);
}
}
public class TechnicalException extends Exception {
public TechnicalException(String message) {
super(message);
}
}
- 下层方法声明异常:下层方法在声明时,使用
throws
关键字声明可能抛出的异常。例如:
public class LowerLevel {
public void performTask() throws BusinessException, TechnicalException {
// 业务逻辑,可能抛出异常
if (/* 业务条件 */) {
throw new BusinessException("业务异常信息");
}
if (/* 技术条件 */) {
throw new TechnicalException("技术异常信息");
}
}
}
- 上层方法捕获异常:上层方法使用
try - catch
块捕获异常,并根据不同异常类型进行处理。例如:
public class UpperLevel {
public void handleTask() {
LowerLevel lowerLevel = new LowerLevel();
try {
lowerLevel.performTask();
} catch (BusinessException e) {
// 处理业务异常
System.err.println("处理业务异常: " + e.getMessage());
} catch (TechnicalException e) {
// 处理技术异常
System.err.println("处理技术异常: " + e.getMessage());
}
}
}
避免常见误区
- 资源正确关闭:
- 使用
try - with - resources
语句:在处理需要关闭资源(如文件流、数据库连接等)的操作时,使用try - with - resources
语句。例如:
- 使用
try (FileInputStream fis = new FileInputStream("file.txt")) {
// 读取文件操作
} catch (IOException e) {
e.printStackTrace();
}
- **确保手动关闭资源**:如果不能使用 `try - with - resources`,在 `finally` 块中手动关闭资源,并在关闭资源时使用 `try - catch` 处理可能的异常。例如:
FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
// 读取文件操作
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 避免过度捕获异常:不要捕获
Exception
或Throwable
等过于宽泛的异常类型,除非有明确需求。应捕获具体的异常类型,这样可以更准确地处理异常,并且不会隐藏代码中的潜在问题。 - 异常信息传递完整性:自定义异常类在构造函数中接受异常信息,并通过
super
传递给父类。在捕获和处理异常时,直接获取异常的message
等信息,确保异常信息不丢失。例如在自定义异常类中:
public class BusinessException extends Exception {
public BusinessException(String message) {
super(message);
}
}
在捕获时:
catch (BusinessException e) {
System.err.println("处理业务异常: " + e.getMessage());
}