即使从不抛出异常,使用try-catch块是否昂贵? [英] Is it expensive to use try-catch blocks even if an exception is never thrown?
问题描述
我们知道捕获异常是很昂贵的。但是,即使从未抛出异常,在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问题/答案 为什么试用块很贵? ,但它适用于。 NET 。
I found the Stack Overflow question/answer Why are try blocks expensive?, but it is for .NET.
推荐答案
尝试
几乎没有任何费用所有。代替在运行时设置 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.
尝试
有一些与之相关的小额费用。 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块!一些异常是异步抛出的,比如在Thread上调用 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屋!