做 java 开发谁没踩过异常的坑?比如空指针直接让程序 “原地去世”,try-catch 裹成 “千层饼”,报错信息含糊到 debug 半小时找不到问题。今天分享 3 个最常用的异常处理技巧,代码简洁还实用,新手也能轻松拿捏~
1. 空指针防护:别再写一堆 if 判空!
日常开发中,空指针是最常见的异常。推荐用objects.requirenonnullelse(java 9+)或optional类,一行搞定空值处理:
import java.util.objects;
import java.util.optional;
public class exceptiondemo {
public static void main(string[] args) {
string username = null; // 模拟可能为空的参数
integer age = null;
// 技巧1:objects工具类(直接指定默认值)
string safename = objects.requirenonnullelse(username, "匿名用户");
system.out.println("用户名:" + safename); // 输出:匿名用户
// 技巧2:optional类(更灵活的空值处理)
integer safeage = optional.ofnullable(age)
.orelse(18); // 为空则返回默认值18
system.out.println("年龄:" + safeage); // 输出:18
// 进阶:为空时抛自定义异常
optional.ofnullable(username)
.orelsethrow(() -> new illegalargumentexception("用户名不能为空!"));
}
}2. 多异常处理:别写 n 个 catch 块!
多个异常只需统一处理时,用 “|” 合并异常类型,代码瞬间清爽:
// 技巧3:合并异常处理(避免重复代码)
public static void handlemultiexception(string str) {
try {
integer num = integer.parseint(str); // 可能抛numberformatexception
system.out.println("转换结果:" + num);
} catch (numberformatexception | nullpointerexception e) {
// 一个catch处理两种异常
system.out.println("错误:输入参数无效!原因:" + e.getmessage());
}
}
// 调用测试
public static void main(string[] args) {
handlemultiexception("abc"); // 抛numberformatexception
handlemultiexception(null); // 抛nullpointerexception
}关键注意事项
别用
e.printstacktrace()!建议用日志框架(如 slf4j)打印,方便定位问题;自定义异常时,要包含详细的错误信息,别只抛 “发生异常” 这种无用提示;
不要滥用 try-catch,比如不需要处理的运行时异常(如 indexoutofboundsexception),不如让程序快速失败,便于排查问题。
额外神操作:统一异常处理 + 错误码
使用 @controlleradvice + @exceptionhandler 统一返回结构体,避免 controller 层到处 try-catch。
@restcontrolleradvice
public class globalexceptionhandler {
@exceptionhandler(bizexception.class)
public result<?> handlebiz(bizexception e) {
return result.error(e.getcode(), e.getmessage());
}
}总结
到此这篇关于java异常处理3个避坑神操作总结的文章就介绍到这了,更多相关java异常避坑神操作内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论