啪啪,打脸了!领导说:try-catch必须放在循环体外!

scope_guard:一种易于使用但难以滥用的现代C ++范围保护 立即下载

今天给大家带来的是关于 try-catch 应该放在循环体外,还是放在循环体内的文章,我们将从性能和业务场景分析这两个方面来回答此问题。

很多人对 try-catch 有一定的误解,比如我们经常会把它(try-catch)和“低性能”直接画上等号,但对 try-catch 的本质(是什么)却缺少着最基础的了解,因此我们也会在本篇中对 try-catch 的本质进行相关的探索。

img

 

 

小贴士:我会尽量用代码和评测结果来证明问题,但由于本身认知的局限,如有不当之处,请读者朋友们在评论区指出。

性能评测

话不多说,我们直接来开始今天的测试,本文我们依旧使用 Oracle 官方提供的 JMH(Java Microbenchmark Harness,JAVA 微基准测试套件)来进行测试。

首先在 pom.xml 文件中添加 JMH 框架,配置如下:

<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
   <groupId>org.openjdk.jmh</groupId>
   <artifactId>jmh-core</artifactId>
   <version>{version}</version>
</dependency>
复制代码

完整测试代码如下:

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

/**
 * try - catch 性能测试
 */
@BenchmarkMode(Mode.AverageTime) // 测试完成时间
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 1, time = 1, timeUnit = TimeUnit.SECONDS) // 预热 1 轮,每次 1s
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS) // 测试 5 轮,每次 3s
@Fork(1) // fork 1 个线程
@State(Scope.Benchmark)
@Threads(100)
public class TryCatchPerformanceTest {
    private static final int forSize = 1000; // 循环次数
    public static void main(String[] args) throws RunnerException {
        // 启动基准测试
        Options opt = new OptionsBuilder()
                .include(TryCatchPerformanceTest.class.getSimpleName()) // 要导入的测试类
                .build();
        new Runner(opt).run(); // 执行测试
    }

    @Benchmark
    public int innerForeach() {
        int count = 0;
        for (int i = 0; i < forSize; i++) {
            try {
                if (i == forSize) {
                    throw new Exception("new Exception");
                }
                count++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return count;
    }

    @Benchmark
    public int outerForeach() {
        int count = 0;
        try {
            for (int i = 0; i < forSize; i++) {
                if (i == forSize) {
                    throw new Exception("new Exception");
                }
                count++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
}
复制代码

以上代码的测试结果为:

 

img

 

 

从以上结果可以看出,程序在循环 1000 次的情况下,单次平均执行时间为:

  • 循环内包含 try-catch 的平均执行时间是 635 纳秒 ±75 纳秒,也就是 635 纳秒上下误差是 75 纳秒;
  • 循环外包含 try-catch 的平均执行时间是 630 纳秒,上下误差 38 纳秒。

也就是说,在没有发生异常的情况下,除去误差值,我们得到的结论是:try-catch 无论是在 for 循环内还是 for 循环外,它们的性能相同,几乎没有任何差别。

 

img

 

 

try-catch的本质

要理解 try-catch 的性能问题,必须从它的字节码开始分析,只有这样我能才能知道 try-catch 的本质到底是什么,以及它是如何执行的。

此时我们写一个最简单的 try-catch 代码:

public class AppTest {
    public static void main(String[] args) {
        try {
            int count = 0;
            throw new Exception("new Exception");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
复制代码

然后使用 javac 生成字节码之后,再使用 javap -c AppTest 的命令来查看字节码文件:

➜ javap -c AppTest 
警告: 二进制文件AppTest包含com.example.AppTest
Compiled from "AppTest.java"
public class com.example.AppTest {
  public com.example.AppTest();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_0
       1: istore_1
       2: new           #2                  // class java/lang/Exception
       5: dup
       6: ldc           #3                  // String new Exception
       8: invokespecial #4                  // Method java/lang/Exception."<init>":(Ljava/lang/String;)V
      11: athrow
      12: astore_1
      13: aload_1
      14: invokevirtual #5                  // Method java/lang/Exception.printStackTrace:()V
      17: return
    Exception table:
       from    to  target type
           0    12    12   Class java/lang/Exception
}
复制代码

从以上字节码中可以看到有一个异常表:

Exception table:
       from    to  target type
          0    12    12   Class java/lang/Exception
复制代码

参数说明:

  • from:表示 try-catch 的开始地址;
  • to:表示 try-catch 的结束地址;
  • target:表示异常的处理起始位;
  • type:表示异常类名称。

从字节码指令可以看出,当代码运行时出错时,会先判断出错数据是否在 from 到 to 的范围内,如果是则从 target 标志位往下执行,如果没有出错,直接 goto 到 return。也就是说,如果代码不出错的话,性能几乎是不受影响的,和正常的代码的执行逻辑是一样的。

 

img

 

 

业务情况分析

虽然 try-catch 在循环体内还是循环体外的性能是类似的,但是它们所代码的业务含义却完全不同,例如以下代码:

public class AppTest {
    public static void main(String[] args) {
        System.out.println("循环内的执行结果:" + innerForeach());
        System.out.println("循环外的执行结果:" + outerForeach());
    }
    
    // 方法一
    public static int innerForeach() {
        int count = 0;
        for (int i = 0; i < 6; i++) {
            try {
                if (i == 3) {
                    throw new Exception("new Exception");
                }
                count++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return count;
    }

    // 方法二
    public static int outerForeach() {
        int count = 0;
        try {
            for (int i = 0; i < 6; i++) {
                if (i == 3) {
                    throw new Exception("new Exception");
                }
                count++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
}
复制代码

以上程序的执行结果为:

java.lang.Exception: new Exception

at com.example.AppTest.innerForeach(AppTest.java:15)

at com.example.AppTest.main(AppTest.java:5)

java.lang.Exception: new Exception

at com.example.AppTest.outerForeach(AppTest.java:31)

at com.example.AppTest.main(AppTest.java:6)

循环内的执行结果:5

循环外的执行结果:3

可以看出在循环体内的 try-catch 在发生异常之后,可以继续执行循环;而循环外的 try-catch 在发生异常之后会终止循环。

因此我们在决定 try-catch 究竟是应该放在循环内还是循环外,不取决于性能(因为性能几乎相同),而是应该取决于具体的业务场景。

例如我们需要处理一批数据,而无论这组数据中有哪一个数据有问题,都不能影响其他组的正常执行,此时我们可以把 try-catch 放置在循环体内;而当我们需要计算一组数据的合计值时,只要有一组数据有误,我们就需要终止执行,并抛出异常,此时我们需要将 try-catch 放置在循环体外来执行。

 

img

 

 

总结

本文我们测试了 try-catch 放在循环体内和循环体外的性能,发现二者在循环很多次的情况下性能几乎是一致的。然后我们通过字节码分析,发现只有当发生异常时,才会对比异常表进行异常处理,而正常情况下则可以忽略 try-catch 的执行。但在循环体内还是循环体外使用 try-catch,对于程序的执行结果来说是完全不同的,因此我们应该从实际的业务出发,来决定到 try-catch 应该存放的位置,而非性能考虑。


 

ScopeGuard:仅标头的现代C ++ ScopeGuard工具可提供多种用法,这些用法简单易用 ScopeGuard 仅标头的现代C ++ ScopeGuard工具可提供多种用法,这些用法简单易用。 注意:即将完成,但需要更多测试。 简单的例子 有3种使用ScopeGuard的方法: 将离开当前作用域时执行的代码放在代码块ON_SCOPE_EXIT {}中。 # include " ScopeGuard.h " ... { ... ON_SCOPE_EXIT{ // callback statments // such as releasing resources }; ... } // callback statments are executed at this point 放在SCOPEGUARD()中可调用 ... { void my_callback (); ... SCOPE 立即下载

相关推荐

5分钟搞定!用Keil MDK将STM32F103C8T6工程无缝迁移到ZET6开发板

本文详细介绍了如何在Keil MDK环境下快速将STM32F103C8T6工程迁移到ZET6开发板,涵盖硬件差异对比、工程配置调整、外设适配及编译排错等关键步骤,帮助开发者5分钟内完成工程移植,大幅提升开发效率。

weixin_30879169的博客 411

在foreach循环程序数据库时try和catch的使用

(当时是测试老胡发现的),后经排查是因为foreach循环体放到了try捕捉异常catch内部了,即第2种情况。一般用于批量写数据时,要求数据一致性的话,需要修改下面的程序,加上事务处理。//第2种是foreach放入try内部中:当其中1条数据插入异常时,会终止循环,不会再执行下一条语句,跳到catch中。第1种方式是把try放入foreach循环体内部中:这种情况当其中1条数据插入异常时,不会影响下一条语句继续执行。Log::error("SQL异常: ".$e->getMessage());

webnoties的专栏 1568

圆极化天线特性测试

3、将测试数据代入方向图计算程序,得到圆极化天线的H面的左旋圆极化分量的方向图和右旋圆极化分量的方向图,其中幅度较大的是主极化。1、固定好待测圆极化天线,打开方向图LABVIEW测试程序,设定测试起始频率,测量待测天线的S21的幅度P1。% title('左旋圆极化方向图','FontSize',15,'Color','b');% title('右旋圆极化方向图','FontSize',15,'Color','b');title('天线的轴比','FontSize',15,'Color','b');

Symean的博客 3377

JAVA中FOR循环中的的TRY-CATCH

JAVA中FOR循环中的的TRY-CATCH 异常处理 当for循环遇上try-catch 首先是不建议在循环体内部进行try-catch操作,效率会非常低,这里仅仅是测试这种情况,具体的业务场景建议还是不要在循环里try-catch @Test public void forThrow(){ final int size = 6; for (int i=0; i<size; i++){ if(i &g...

weixin_42338707的博客 9652

SAP EWM 内向交货流程(一)

本文介绍了SAP EWM系统中内向交货单的基本配置与操作流程。

huqinghai的专栏 2412

SECS/GEM协议库及开源代码

以下是在开发SECS/GEM协议过程中,在网络上搜集协议实现资源,希望对SECS/GEM协议感兴趣的同学能有所帮助。 开源代码 freesecs FREESECS 是一个开源的SEMI SECS协议库,采用C++语言实现,可运行于Linux, MacOS X, NetBSD。 实现协议:E37.1、E5 开源地址:freesecs download | SourceForge.net 下载地址:https://download.csdn.net/download/BT_LEO/24305429

码农的历程 9965

用Scope Guard 范围守卫实现超方便的RAII

上一篇文章写了怎么构建一个类来实现RAII但是看起来还是挺麻烦的网上搜了一圈发现一个Scope Guard 范围守卫。

XiaoWuiiii的博客 462

《科研伦理与学术规范》 全部 习题_答案 2020年秋

科研伦理与学术规范 答案 文章目录科研伦理与学术规范 答案1. 第一章课后习题(必做) 答案1.1 第一章Demo2. 第二章课后习题(必做) 答案3. 第三章课后习题(必做) 答案4. 第四章课后习题(必做) 答案5. 第五章课后习题(必做) 答案6. 第六章课后习题(必做) 答案 # 每行5题 #写于2020.11.17 侵删 1. 第一章课后习题(必做) 答案 ABC, A, B ,D ,ABCD ABC, D, A, BCD, C D, D, 1.1 第一章Demo

羊老羊 25万+

C++ ScopeGuard

一般情况下申请对象资源时候使用RAII应该可以满足需求,但总有些情况下不需要深度包装的对象申请时候是不太合适这些方案的,如果有需求的时候,可以参考下如下代码。 class noncopyable { protected: noncopyable() = default; ~noncopyable() = default; noncopyable(const noncopyable& _) = delete; noncopyable& operator=(const noncopyab

degawong的博客 1675

SUMO使用教程(一)

本人的sumo视频入门课程,希望支持哦。https://edu.csdn.net/course/detail/25834 SUMO是一款交通仿真软件,其余可自行百度。教程一主要展示一下如何运行一个仿真实例。当然,这只是实现方法中的一种。 准备: 1.SUMO软件 2.osm地图文件 SUMO可去官网下载,解压后就可以使用,图形界面软是在解压后bin文件夹下的sumo-gui.exe。...

lyx的专栏 3万+

Allegro如何进行四层板板层设计

板层的设计

weixin_42499230的博客 3212

推荐一个不可或缺的C++11神器:scope_guard

推荐一个不可或缺的C++11神器:scope_guard 项目地址:https://gitcode.com/gh_mirrors/sc/scope_guard 在C++编程中,确保资源在完成其工作后正确释放是至关重要的。这就是我们引入scope_guard的原因,一个轻量级、高效且灵活的C++11范围保护库,它能确保即使在异常情况下也能执行清理操作。 项目介绍 scope_guard是一个单头文件...

gitblog_00032的博客 1136

Carla运行显示The following component(s) are required to run this program:DirectX Runtime |nvapi64.dll没有被

Carla运行显示The following component(s) are required to run this p 参考: 【1】EPIC 启动游戏提示The following component(s) are required to run this program:... - 『悬赏问答区』 - 吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cnhttps://www.52pojie.cn/thread-1485651-1-1.html ...

anananajiushiwo的博客 5万+

啪啪打脸!领导说:try-catch要放在循环体外!

这是我的第206期分享作者 | 王磊来源 | Java中文社群(ID:javacn666)转载请联系授权(微信ID:GG_Stone)哈喽,亲爱的小伙伴们,技术学磊哥,进步没得说!欢...

磊哥聊Java 1469

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

java try catch_啪啪打脸!领导说:try-catch要放在循环体外!

来源:Java中文社群 今天给大家带来的是关于 try-catch 应该放在循环体外,还是放在循环体内的文章,我们将从性能和业务场景分析这两个方面来回答此问题。很多人对 try-catch 有一定的误解,比如我们经常会把它(try-catch)和“低性能”直接画上等号,但对 try-catch 的本质(是什么)却缺少着最基础的了解,因此我们也会在本篇中对 try-catch 的本质进行相关...

weixin_39779528的博客 88

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java try catch_啪啪,打脸了!领导说:try-catch必须放在循环体外!

哈喽,亲爱的小伙伴们,技术学磊哥,进步没得说!欢迎来到新一期的性能解读系列,我是磊哥。今天给大家带来的是关于 try-catch 应该放在循环体外,还是放在循环体内的文章,我们将从性能和业务场景分析这两个方面来回答此问题。很多人对 try-catch 有一定的误解,比如我们经常会把它(try-catch)和“低性能”直接画上等号,但对 try-catch 的本质(是什么)却缺少着最基础的了解,因此...

weixin_39842955的博客 171

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

ScopeGuard的使用

ScopeGuard的使用:Boost.ScopeExit、loki-lib.ScopeGuard

大草的博客 1363

java foreach循环抛异常

场景: foreach 循环中,每次都需要http请求,http请求会抛出异常。idea会自动提示 try…catch 但是此时,是 循环中内部try…catch,catch则无法向外throw异常。 初步解决:把try…catch放到整个foreach 循环外面,但是依旧存在循环内部需要try…catch 解决: 把try…catch放到整个循环外面,如果使用普通的for循环,自己设定索引i 进行循环,就可以成功在catch中向外抛异常 ...

封神之路 5564

Java基础(4)——逻辑控制 分支,循环,try...catch,递归 & break, continue, return

1.while循环+break的组合使用;2.逻辑控制词continue,break,return的灵活使用;3.递归思想初步,自己调用自己;4.try-catch异常捕获初步;

Arya的博客,专注后端领域 744

为什么foreach方法里面的异常无法在foreach外层进行try catch捕获

在 Spring Boot 中使用 Java 中的Iterable接口的forEach方法进行迭代时,如果forEach方法内部的代码抛出异常,而你尝试在外层的try-catch块中捕获这些异常,通常会出现捕获不到异常的情况。这是因为异常捕获的作用域是基于代码块的。Lambda 表达式的异常捕获是局部的,是由于其设计初衷和语法限制所决定的。这种设计保证了 Lambda 表达式的简洁性和一致性,同时也需要开发者在使用 Lambda 表达式时,充分考虑和处理可能发生的异常,以确保程序的稳定性和可靠性。

xiaodaidai的博客 1893
上一篇: Java岗位这么多,主要运用在哪些地方呢?优缺点分析
下一篇: IDEA同款数据库管理工具,提示太全了,用起来贼香!
Java斗帝之路
博客等级 码龄7年 2391粉丝 686原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址