自定义异常类
-
需求:在项目中 需要限制某些参数
-
实现:
import lombok.extern.slf4j.Slf4j;
import java.util.Scanner;
/**
* @author nzh
* @date:2022/3/18 16:23
* @desc:
*/
@Slf4j
public class PixelConversion {
public static void main(String[] args) {
String address;
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
try {
address = input.nextLine();
if (address.length() > 10) {
//判断地址长度 抛出异常
throw new StrRangeException("地址有误,长度过长!");
}
} catch (StrRangeException e) {
//打印错误信息 用日志 不会造成错误信息过多 应用挂掉
log.error("-**-",e);
}
}
}
//自定义异常类 继承Exception 创建两个构造参数
static class StrRangeException extends Exception {
public StrRangeException() {
super();
}
public StrRangeException(String message) {
super(message);
}
}
}
- 注意事项:e.printStackTrace() 可能会导致锁死,Springboot中 用Slf4j 控制台加日志输出错误信息