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

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

问题描述

有<一个href="http://stackoverflow.com/questions/134698/catching-exceptions-as-expected-program-execution-flow-control">an有趣的帖子在这里这一点,就控制跨应用程序流。

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

嗯,最近,我遇到了一个有趣的问题。生成的第n个值在可能(几乎)无穷的递归序列。这种特殊的算法将在ATLEAST 10-15堆栈引用深,它成功的地步。我首先想到的是抛出一个SuccessException,看上去像这样(C#):

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;
    }
}

然后做这样的事情:

Then do something like this:

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方法,你应该有一些返回值,抛出一个异常,表明成功,并不是一种普遍的做法,并以最低的将是非常混乱的任何人看到了code。且不说与异常相关的开销。

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天全站免登陆