gpt4 book ai didi

c# - 吞下异常时如何返回值?

转载 作者:行者123 更新时间:2023-11-30 19:29:32 25 4
gpt4 key购买 nike

我在我的数据类中对 catch block 使用了以下模式:

} catch (OracleException e) {
log.Error(e, e);
ExceptionNotification.Show(e, "Platypus data not found for Platypus");
throw;
}

(“日志”是 log4net;之后是我们奇特的异常显示对话框)。

当我删除“抛出”时,我得到“并非所有代码路径都返回一个值”

如果我到达异常 block ,我要返回的对象(OracleDataTable、List、Dictionary<> 或自定义类,通常可能为 null,或者充其量感觉不太好。我能做什么返回来安抚编译器?

最佳答案

声明返回类型的方法的每个代码路径都必须返回值或抛出异常。

如果不想抛出,必须返回一个合适的值

} catch (OracleException e) {
log.Error(e, e);
ExceptionNotification.Show(e, "Platypus data not found for Platypus");
return SomeMeaningfulReturnValue;
}

但是,除非您可以返回的值对调用者实际上有意义(而不是说返回 null 并发明一个“null 意味着有问题”的代码契约),否则我会坚持当出现异常情况时抛出异常的约定。

关于c# - 吞下异常时如何返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11996060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com