性能提示:避免捕获异常
💡一则或许对你有用的小广告
欢迎加入小哈的星球 ,你将获得:专属的项目实战 / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论
- 新项目:《从零手撸:仿小红书(微服务架构)》 正在持续爆肝中,基于
Spring Cloud Alibaba + Spring Boot 3.x + JDK 17...
,点击查看项目介绍 ;- 《从零手撸:前后端分离博客项目(全栈开发)》 2 期已完结,演示链接: http://116.62.199.48/ ;
截止目前, 星球 内专栏累计输出 82w+ 字,讲解图 3441+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,权限管理,Spring Cloud Alibaba 微服务等等,已有 2800+ 小伙伴加入学习 ,欢迎点击围观
在这篇文章中,我们将通过一个简单的示例来了解捕获异常如何影响性能。
代码示例
捕获异常的代码
private static void exceptionTest(){
int i=0;
int j=1;
try{
int k=j/i;
}catch(ArithmeticException ex){
//not good idea to catch run time exception but catch for demo only
}
}
处理条件的代码
private static void exceptionTest(){
int i=0;
int j=1;
try{
int k=j/i;
}catch(ArithmeticException ex){
//not good idea to catch run time exception but catch for demo only
}
}
调用逻辑的方法
private static void exceptionTest(){
int i=0;
int j=1;
try{
int k=j/i;
}catch(ArithmeticException ex){
//not good idea to catch run time exception but catch for demo only
}
}
主要方法
private static void exceptionTest(){
int i=0;
int j=1;
try{
int k=j/i;
}catch(ArithmeticException ex){
//not good idea to catch run time exception but catch for demo only
}
}
结果
结论
避免捕获异常,因为它会减少响应时间。上面的示例演示了一个简单的单线程应用程序的结果;然而,在多线程环境中情况会变得更糟。