springboot 写一个自定义异常
时间: 2023-02-14 15:28:33 浏览: 91
在 Spring Boot 中创建自定义异常可以按照以下步骤进行:
1. 创建一个继承自 `java.lang.Exception` 的异常类,可以添加自定义的属性和方法。
2. 在需要抛出该异常的地方,使用 `throw` 关键字抛出该异常。
3. 在捕获该异常的地方,使用 `try-catch` 语句进行捕获。
例如,如果你想创建一个名为 `UserNotFoundException` 的异常,你可以这样写:
```java
public class UserNotFoundException extends Exception {
private long userId;
public UserNotFoundException(long userId) {
super(String.format("User with ID %d not found", userId));
this.userId = userId;
}
public long getUserId() {
return userId;
}
}
```
然后,在你的代码中,你就可以这样抛出该异常:
```java
long userId = 1;
User user = findUserById(userId);
if (user == null) {
throw new UserNotFoundException(userId);
}
```
最后,你可以在你的代码中使用 `try-catch` 语句来捕获这个异常:
```java
try {
// 代码
} catch (UserNotFoundException ex) {
// 处理异常
}
```
希望这对你有帮助!
阅读全文
相关推荐
















