即使从未抛出异常,使用 try-catch 块是否昂贵? [英] Is it expensive to use try-catch blocks even if an exception is never thrown?

查看:35
本文介绍了即使从未抛出异常,使用 try-catch 块是否昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道捕获异常的代价很高.但是,即使从未抛出异常,在 Java 中使用 try-catch 块也很昂贵吗?

We know that it is expensive to catch exceptions. But, is it also expensive to use a try-catch block in Java even if an exception is never thrown?

我找到了 Stack Overflow 问题/答案为什么 try 块很昂贵?,但它适用于 .NET.

I found the Stack Overflow question/answer Why are try blocks expensive?, but it is for .NET.

推荐答案

try 几乎没有任何费用.代码的元数据不是在运行时设置 try 的工作,而是在编译时进行结构化,这样当抛出异常时,它现在执行一个相对昂贵的操作,即走上堆栈并查看如果存在可以捕获此异常的任何 try 块.从外行的角度来看,try 也可能是免费的.它实际上是抛出异常让你付出代价 - 但除非你抛出成百上千个异常,否则你仍然不会注意到成本.

try has almost no expense at all. Instead of doing the work of setting up the try at runtime, the code's metadata is structured at compile time such that when an exception is thrown, it now does a relatively expensive operation of walking up the stack and seeing if any try blocks exist that would catch this exception. From a layman's perspective, try may as well be free. It's actually throwing the exception that costs you - but unless you're throwing hundreds or thousands of exceptions, you still won't notice the cost.

try 有一些与之相关的小成本.Java 无法对 try 块中的代码进行一些优化,否则它会这样做.例如,Java 通常会重新安排方法中的指令以使其运行得更快——但 Java 还需要保证如果抛出异常,则观察方法的执行,就像执行源代码中编写的语句一样为了达到某些行.

try has some minor costs associated with it. Java cannot do some optimizations on code in a try block that it would otherwise do. For example, Java will often re-arrange instructions in a method to make it run faster - but Java also needs to guarantee that if an exception is thrown, the method's execution is observed as though its statements, as written in the source code, executed in order up to some line.

因为在 try 块中可以抛出异常(在 try 块中的任何行!一些异常是异步抛出的,例如通过在线程上调用 stop(已弃用),甚至除了 OutOfMemoryError 几乎可以在任何地方发生)但它可以被捕获并随后以相同的方法继续执行代码,更难以推理可以进行的优化,因此它们更少可能会发生.(有人必须编写编译器来执行它们,推理并保证正确性等.对于意味着异常"的东西来说,这将是一个很大的痛苦)但同样,在实践中你不会注意到这样的事情.

Because in a try block an exception can be thrown (at any line in the try block! Some exceptions are thrown asynchronously, such as by calling stop on a Thread (which is deprecated), and even besides that OutOfMemoryError can happen almost anywhere) and yet it can be caught and code continue to execute afterwards in the same method, it is more difficult to reason about optimizations that can be made, so they are less likely to happen. (Someone would have to program the compiler to do them, reason about and guarantee correctness, etc. It'd be a big pain for something meant to be 'exceptional') But again, in practice you won't notice things like this.

这篇关于即使从未抛出异常,使用 try-catch 块是否昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆