简体   繁体   English

是否被应用到不具有的try-catch错误抛出一个异常的函数在JVM优化?

[英]Does the JVM optimization being applied to a function that doesn't have try-catch bug throws a exception?

There is a question What is the difference between try-catch and throws Exception in terms of performance? 有一个问题,就性能而言,try-catch和throws Exception什么区别? .

A follow-up question is "Does the JVM optimization being applied to a function that doesn't have try-catch bug throws a exception?". 后续问题是“将JVM优化应用于没有try-catch错误的函数会引发异常吗?”。 For example, all methods throw their exceptions and the main method has a try-catch to surround all methods and codes. 例如,所有方法都抛出异常,而main方法具有try-catch来包围所有方法和代码。 In this case, according to "Effective Java": 在这种情况下,根据“有效的Java”:

Placing code inside a try-catch block inhibits certain optimizations that modern JVM implementations might otherwise perform. 将代码放在try-catch块中会禁止现代JVM实现可能执行的某些优化。

JVM won't do some optimization for the code in the main method. JVM不会对main方法中的代码做一些优化。 The question is: dose the JVM optimize the code in those methods who throw exceptions? 问题是:在那些抛出异常的方法中,JVM是否优化了代码?

If you mean the throws clause, then definitely not. 如果您是说throws子句,那么绝对不是。 Note that all methods sort of have an "invisible throws RuntimeException, Error clause", ie, they may throw something. 请注意,所有方法都具有“不可见的throws RuntimeException, Error子句”,即,它们可能会抛出一些东西。

Note also, that there's nothing like checked exceptions on the JVM level, it's a pure Java source feature which doesn't exist in the bytecode (and there are many other languages running on the JVM and having no checked exceptions; AFAIK Java is the only experiment). 还要注意,在JVM级别上没有类似检查异常的东西,它是字节码中不存在的纯Java源功能(并且有许多其他语言在JVM上运行并且没有检查异常; AFAIK Java是唯一的实验)。

Actually throwing exceptions is expensive, but basically any method can throw some. 实际上,抛出异常的代价很高,但是基本上任何方法都可以抛出异常。 Even an empty method can in theory throw a StackOverflowError . 理论上,即使是空方法也可以引发StackOverflowError It only gets expensive, when an exception actually happens. 当异常确实发生时,它才变得昂贵。

For a try-catch block, there's just an entry somewhere which gets consulted, when an exception gets actually thrown, otherwise it doesn't get used. 对于try-catch块,当实际抛出异常时,在某处只有一个条目可供参考,否则就不会被使用。 It may prevent some optimizations, which would make it impossible to use this information, or not; 它可能会阻止某些优化,从而导致无法使用或无法使用此信息; the JVM gets better and better. JVM越来越好。

Anyway, adding a throws clause has no performance impact and it's the right thing most of the time. 无论如何,添加throws子句不会影响性能,并且在大多数情况下是正确的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM