Are compilers allowed to optimize-out exception throws?

核能气质少年 提交于 2019-12-03 05:49:59
newfurniturey

"Are compilers smart enough" seems to hint that Exceptions don't serve a purpose in your project and, if that's the case, you shouldn't use them in the first place (unless of course you actually have the possibility of getting an exception).

Short-answer: No, compilers will not remove your exceptions / exception handling based on the pattern you're using them.

When you use a try/catch, the exception it handles is added to the main exception table; this table can be monitored, hooked into, added on and removed from. Just because you catch the exception right away doesn't mean other things aren't happening with it as well.

Side Source:
A paper was written on Optimizing Away C++ Exception Handling that outlines all (almost all) current implementations of optimizations pertaining to exceptions. Throughout it, it shows that at the current time they are not stripped at compile-time but optimizations are made to them. The paper itself recommends enhancements to EH (Exception Handling) to remove the unnecessary exceptions and, overall, is a pretty good read.

UPDATE (additional sources)
Looking further into the topic, the GCC compiler appears to not optimize away exceptions; however, it does offer an option to do so: -fno-exceptions. This option will remove all exceptions and directly replace them with abort() calls.

Another source (here on StackOverflow) doesn't directly mention "removing exceptions" but does outline the two optimizations made to exceptions, setjmp/longjmp and Zero-Cost. It can be inferred by the highlighting of the actual enhancements without mention of "completely removing the exception" that there is no such optimization (yet, at least with the mentioned compilers). Another source with more detailed info on these optimizations can be found here.

The repetition in your code can trivially be removed with a simple loop:

int foo()
{
    for (int x : {1, 2, 3, 4})
    {
        int err = some_call(x);
        if (err != 0) return err;
    }
    bar();
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!