性能提示:避免捕获异常

一则或许对你有用的小广告

欢迎加入小哈的星球 ,你将获得:专属的项目实战 / Java 学习路线 / 一对一提问 / 学习打卡/ 赠书活动

目前,正在 星球 内带小伙伴们做第一个项目:全栈前后端分离博客项目,采用技术栈 Spring Boot + Mybatis Plus + Vue 3.x + Vite 4手把手,前端 + 后端全栈开发,从 0 到 1 讲解每个功能点开发步骤,1v1 答疑,陪伴式直到项目上线,目前已更新了 204 小节,累计 32w+ 字,讲解图:1416 张,还在持续爆肝中,后续还会上新更多项目,目标是将 Java 领域典型的项目都整上,如秒杀系统、在线商城、IM 即时通讯、权限管理等等,已有 870+ 小伙伴加入,欢迎点击围观

在这篇文章中,我们将通过一个简单的示例来了解捕获异常如何影响性能。

代码示例

捕获异常的代码


 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
 }
 }

结果












结论

避免捕获异常,因为它会减少响应时间。上面的示例演示了一个简单的单线程应用程序的结果;然而,在多线程环境中情况会变得更糟。