C#:相当于python try / catch / else块 [英] C#: Equivalent of the python try/catch/else block

查看:127
本文介绍了C#:相当于python try / catch / else块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,有一个非常有用的异常处理代码:

In Python, there is this useful exception handling code:

try:
    # Code that could raise an exception
except Exception:
    # Exception handling
else:
    # Code to execute if the try block DID NOT fail

我认为可以将可能的代码与正常代码进行分离是非常有用的。在Python中,这是可能的,如上所示,但是我在C#中找不到任何东西。

I think it's useful to be able to separate the code that could raise and exception from your normal code. In Python, this was possible as shown above, however I can't find anything like it in C#.

假设这个功能或类似的功能不存在,在 try 块或 catch 块之后放入正常代码的标准做法

Assuming the feature or one like it doesn't exist, is it standard practice to put normal code in the try block or after the catch block?

我问的原因是因为我有以下代码:

The reason I ask is because I have the following code:

if (!IsReadOnly)
{
    T newobj;
    try
    {
        newobj = DataPortal.Update<T>(this);

        List<string> keys = new List<string>(BasicProperties.Keys);
        foreach (string key in keys)
        {
            BasicProperties[key] = newobj.BasicProperties[key];
        }
    }
    catch (DataPortalException)
    {
        // TODO: Implement DataPortal.Update<T>() recovery mechanism
    }
}

这需要正常代码在try块中,否则如果引发异常,随后处理, newobj 将被取消分配,但在try块中有这么多的代码感觉相当不自然,这与$ code> DataPortalException 。做什么?

Which requires the normal code to be in the try block because otherwise if an exception was raised and subsequently handled, newobj would be unassigned, but it feels quite unnatural to have this much code in the try block which is unrelated to the DataPortalException. What to do?

谢谢

推荐答案

我宁愿看在try / catch之外的其他代码,所以很清楚你正在尝试捕获的异常来自哪里,并且你不会意外地捕获一个你不想捕获的异常。

I would prefer to see the rest of the code outside the try/catch so it is clear where the exception you are trying to catch is coming from and that you don't accidentally catch an exception that you weren't trying to catch.

我认为最接近Python的try / catch / else是使用本地布尔变量来记住异常是否被抛出。

I think the closest equivalent to the Python try/catch/else is to use a local boolean variable to remember whether or not an exception was thrown.

bool success;

try
{
    foo();
    success = true;
}
catch (MyException)
{
    recover();
    success = false;
}

if (success)
{
    bar();
}

但是,如果你这样做,我会问你为什么不可以从异常完全恢复,以便您可以像成功一样继续,或者通过返回错误代码完全中止,甚至只是将异常传播给调用者。

But if you are doing this, I'd ask why you don't either fully recover from the exception so that you can continue as if there had been success, or else fully abort by returning an error code or even just letting the exception propagate to the caller.

这篇关于C#:相当于python try / catch / else块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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