只是“扔"东西有好处吗?抓住了吗? [英] Is there a benefit to JUST a "throw" in a catch?

查看:34
本文介绍了只是“扔"东西有好处吗?抓住了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

曾经与一位同事进行过激烈的辩论,讨论他如何将自己的大部分功能包装在一次尝试/接球中,但是该接球只是其中的一个掷球".

 私有子foo()尝试'做一点事'抓住扔没别的!"结束尝试结束子 

我的想法是不打扰(假设此时您无需执行任何操作)-异常会冒泡到父成员中的下一个异常处理程序.

听起来唯一合理的论点是,有时未捕获到异常并且您的代码停止了(在调试模式下),当前行以绿色突出显示了……这可能与多个线程有关吗?最佳做法的确说明了每个线程都有一个异常处理程序",但大多数情况下我们是单线程的.

好处可能是,它在调试模式下可能不会突然弹出给父成员(是,乔尔!),这很有用-您将移至"throw"语句并能够检查您的本地人.但是然后您的代码会被try/catch/throws弄乱了"(在这里引用另一个线程)?

如果没有异常发生,那么在各处添加try/catch/throws会涉及什么样的开销(即,您应该避免在紧缩循环中进行try/catch)吗?

解决方案

您在catch中有一个单独的抛出而不是抛出新的异常的原因是因为这会导致原始堆栈跟踪/异常数据得以保留.之所以这么做,是因为您现在可以在此处设置一个断点进行调试.

Been having a "heated debate" with a colleague about his practice of wrapping most of his functions in a try/catch but the catch has JUST a "throw" in it e.g.

Private sub foo()
    try
        'Do something'
    catch
        throw 'And nothing else!'
    End Try
End Sub

My thought was to not even bother (assuming you don't need to do anything at this point) - the exception would bubble to the next exception handler in a parent member.

The only argument that sounded plausible was that sometimes exceptions weren't caught and your code stopped (in debug mode) with the current line highlighted in green...and that this may be something to do with multiple threads? Best practice does state "an exception handler for each thread" but mostly we work single-threaded.

The good thing may be it could be useful in debug mode to not suddenly pop out to a parent member (yes, Joel!) - you'd move to the "throw" statement and be able to examine your locals. But then your code would be "littered with try/catch/throws" (to quote another thread here)?

And what sort of overhead would be involved in adding try/catch/throws everywhere if no exception occurs (i.e. should you avoid try/catches in tight loops)?

解决方案

The reason you have a lone throw inside a catch rather than throwing a new exception is because this causes the original stack trace/exception data to be preserved. And one reason you might do this is because you can now set a break-point there for debugging.

这篇关于只是“扔"东西有好处吗?抓住了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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