且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

try/catch块的性能问题?

更新时间:2023-11-29 14:43:22

使用try/catch是一种好习惯吗?"不只是这个.

不使用try/catch绝对不是一个好习惯.唯一可以接受的选择是不关心错误和其他异常情况(是的,在某些情况下这是完全可以接受的).

现在,按定义,try/catch不再是性能问题.如果您需要异常处理,那是不可避免的,如果您使用任何其他方式的错误处理(我什至不提这个想法),都会使性能变得更差.

不过,我发现尝试/捕获通常会带来巨大的性能问题.是的,相互矛盾的段落在起作用.我在上一段中所说的假定该代码是由非白痴编写的.但是,在现实生活中,您了解. :-)

尝试/捕获应该很少使用.理想情况下-一次出现在每个线程的堆栈顶部(以防止终止),并且一次出现在UI的主事件周期中.每次发生异常情况时都应该使用抛掷(顾名思义,并非总是错误,某些异常情况;经典示例:核反应堆过热").我们不会在特殊情况下浪费CPU时间,对.尝试/捕获的另一种情况-主要处理情况;试试/最后应该更典型;关闭文件句柄,处理等.

实际上,结构异常处理可以节省很多性能.程序设计应该更具进攻性,而不应具有防御性.不需要大多数检查.

请参阅我过去的答案中的一些建议:
我如何制作滚动条到达底部时将停止的循环 [当我运行应用程序时,异常是捕获了如何处理? [ throw. .then ... rethrowing [ ^ ],
未处理的异常:访问冲突 [
"Using try/catch is a good practice?" Not just this.

Not using try/catch is impossibly bad practice. The only acceptable alternative is not caring about errors and other exceptional conditions (yes, this is quite acceptable in some cases).

Now, try/catch can not be an issue of performance by definition. If you need exception handling, there are unavoidable, if you use any other way of error handling (I hate even mentioning the idea), you make performance much worse.

Nevertheless, I see that try/catch pretty often present huge performance problem. Yes, contradictory paragraphs in action. What I say in the previous paragraph assumed that the code is written by non-idiots. In real life, however… well, you understand. :-)

Try/catch should be used quite rarely. Ideally — once on the top of the stack of each thread (to prevent termination) and also in the main event cycle of the UI. Throw should be uses every time exceptional situation happens (not always an error, some exceptional situations, as the name suggests; classical example: "nuclear reactor overheated"). We do not spare CPU time for really exceptional situations, right. Another case of try/catch — primary specialize processing of the situation; try/finally should be more typical; close file handles, dispose, etc.

Actually, structure exception handling saves a lot of performance. Programming should be more offensive and less defensive. Most checks are not needed.

See some of my recommendations in my past answers:
How do i make a loop that will stop when a scrollbar reaches the bottom[^],
When i run an application an exception is caught how to handle this?[^],
throw . .then ... rethrowing[^],
Unhandled Exception : Access Violation[^].

Only last answer was about C++, but most recommendations are applicable to many platforms/languages.

—SA