gpt4 book ai didi

c# - Try - Catch 返回策略

转载 作者:太空狗 更新时间:2023-10-29 22:17:26 24 4
gpt4 key购买 nike

在方法中使用 try-catch 时,如果您希望应用程序在出现错误时继续运行,是否可以通过 catch block 返回默认值并记录错误?供以后审查?

例如:

public static string GetNameById(int id)
{
string name;
try
{
//Connect to Db and get name - some error occured
}
catch(Exception ex)
{
Log(ex);
name = String.Empty;
}

return name;
}

示例 2:

public static string GetIdByName(string name)
{
int id;
try
{
//Connect to Db and get id- some error occured
}
catch(Exception ex)
{
Log(ex);
id = 0;
}

return id;
}

是否可以返回任何默认值(取决于方法的返回类型...???)以便需要此方法结果的应用程序逻辑不会崩溃并继续运行....

提前致谢...

问候。

最佳答案

关于异常处理的建议是,大多数情况下,您应该只捕获您可以采取措施的异常(例如重试操作、尝试不同的方法、提高安全性等)。如果您在全局级别的应用程序中的其他地方进行了日志记录,则不需要这种 catch-log-return。

就个人而言 - 通常 - 在这种情况下我会这样做:

public static string GetNameById(int id)
{
string name;
try
{
//Connect to Db and get name - some error occured
}
catch(Exception ex)
{
Log(ex);
throw; // Re-throw the exception, don't throw a new one...
}

return name;
}

像往常一样 - 这取决于。

但要注意其他陷阱,例如调用方法不知道发生故障,并在抛出异常的方法实际有效的假设下继续执行工作。此时,您开始讨论“返回码与抛出异常”,您会在 SO.com 和互联网上找到很多资源。

关于c# - Try - Catch 返回策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4746908/

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