请描述 Java 异常处理中 'custom exception' 的设计和使用方法,并给出一个自定义异常类的示例。
在 Java 中,自定义异常(Custom Exception)通常用于表示应用程序特有的异常情况,以更精确地描述业务逻辑中的错误。自定义异常可以通过继承 Exception 类(检查型异常)或 RuntimeException 类(非检查型异常)来实现。以下是自定义异常的基本设计方法和使用场景。
自定义异常的设计方法
-
继承父类:
- 如果需要强制调用者处理异常,通常继承
Exception类(检查型异常)。 - 如果希望异常可以不被强制捕获,继承
RuntimeException类(非检查型异常)。
- 如果需要强制调用者处理异常,通常继承
-
定义构造方法:
- 提供无参构造方法。
- 提供带有错误信息的构造方法(
String message)。 - 提供带有错误信息和原因异常的构造方法(
String message, Throwable cause)。
-
添加额外字段和方法:
- 根据需要可以为自定义异常添加额外的字段或方法,以提供更多上下文信息。
自定义异常的使用方法
自定义异常的使用方式与 Java 原生异常类似,通常通过 throw 关键字抛出,并通过 try-catch 块捕获。
示例
以下是一个自定义异常类的示例,用于表示用户登录失败的情况:
public class LoginFailedException extends RuntimeException {
private final String username;
private final String reason;
// 无参构造方法
public LoginFailedException() {
super("Login failed");
this.username = "unknown";
this.reason = "unknown";
}
// 带错误信息的构造方法
public LoginFailedException(String message) {
super(message);
this.username = "unknown";
this.reason = "unknown";
}
// 带详细信息的构造方法
public LoginFailedException(String username, String reason) {
super(String.format("Login failed for user '%s'. Reason: %s", username, reason));
this.username = username;
this.reason = reason;
}
// 带错误信息和原因异常的构造方法
public LoginFailedException(String message, Throwable cause) {
super(message, cause);
this.username = "unknown";
this.reason = "unknown";
}
// 获取用户名
public String getUsername() {
return username;
}
// 获取失败原因
public String getReason() {
return reason;
}
}
使用场景示例
以下是一个使用自定义异常的示例,模拟用户登录逻辑:
public class UserService {
private static final String VALID_USERNAME = "admin";
private static final String VALID_PASSWORD = "password123";
public void login(String username, String password) {
if (!VALID_USERNAME.equals(username)) {
throw new LoginFailedException(username, "Invalid username");
}
if (!VALID_PASSWORD.equals(password)) {
throw new LoginFailedException(username, "Invalid password");
}
System.out.println("Login successful");
}
public static void main(String[] args) {
UserService service = new UserService();
try {
service.login("admin", "wrongpassword");
} catch (LoginFailedException e) {
System.err.println(e.getMessage());
System.err.println("Username: " + e.getUsername());
System.err.println("Reason: " + e.getReason());
}
}
}
解释
-
自定义异常的优势:
- 可以明确区分异常的类型,提高代码的可读性。
- 可以通过额外字段和方法提供更多上下文信息。
-
示例输出:
Login failed for user 'admin'. Reason: Invalid password Username: admin Reason: Invalid password
总结来说,自定义异常是 Java 异常处理的重要组成部分,能够帮助开发者更好地管理业务逻辑中的错误情况。