控制流程异常 [英] Exceptions for flow of control

查看:145
本文介绍了控制流程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关这个的一个有趣的帖子关于跨应用程序的控制流程。

There is an interesting post over here about this, in relation to cross-application flow of control.

最近,我遇到了一个有趣的问题。在潜在(实际)无限循环递归序列中生成第n个值。该特定算法将至少在至少10-15个堆栈引用中成功。我的第一个想法是抛出一个看起来像这样(C#)的SuccessException:

Well, recently, I've come across an interesting problem. Generating the nth value in a potentially (practically) endless recursive sequence. This particular algorithm WILL be in atleast 10-15 stack references deep at the point that it succeeds. My first thought was to throw a SuccessException that looked something like this (C#):

class SuccessException : Exception
{
    public string Value
    { get; set; }

    public SuccessException(string value)
        : base()
    {
        Value = value;
    }
}

然后执行以下操作:

try
{
    Walk_r(tree);
}
catch (SuccessException ex)
{
    result = ex.Value;
}

然后我的想法徘徊在这里,我一直听到永远不要使用异常流控制。有没有借口?你会如何构建这样的东西,如果你要实现它?

Then my thoughts wandered back here, where I've heard over and over to never use Exceptions for flow control. Is there ever an excuse? And how would you structure something like this, if you were to implement it?

推荐答案

在这种情况下,我会看着你Walk_r方法,你应该有一些返回值的东西,抛出一个异常来表示成功,这不是常见的做法,至少对任何看到代码的人来说都是非常混乱的。更何况与异常有关的开销。

In this case I would be looking at your Walk_r method, you should have something that returns a value, throwing an exception to indicate success, is NOT a common practice, and at minimum is going to be VERY confusing to anyone that sees the code. Not to mention the overhead associated with exceptions.

这篇关于控制流程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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