gpt4 book ai didi

c# - 在 try block 中尝试 catch - 异常应该调用相同的函数

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

如果我有这样的东西会怎样:

public static void DoSomething()
{
try
{
//some code
try
{
//some other code
}
catch (Exception e)
{
log.Error("At the end something is wrong: " + e);
FunctionA(); //same function as in the first exception
}
}
catch (Exception e)
{
log.Error("At the start something wrong: " + e);
FunctionA();
}
}

所以我尝试捕获另一个。异常应该不同,我想用不同的记录器处理它们。但是假设我想为这两个异常调用相同的函数。我必须写 FunctionA() 两次。这样可以吗?或者这种类型的异常还有其他问题吗?有什么建议吗?

最佳答案

您可以将单个 try block 与多个 catch block 一起使用;也可以使用 finally 语句来执行一些代码段,无论是否有异常。

在一个函数中使用多个 try-catch block 通常不是一个好主意。此外,最好在异常发生的地方处理它。

public static void DoSomething()
{
try
{
//some code
}

catch (ExceptionA e)
{
// exception is ExceptionA type
log.Error("At the end something is wrong: " + e);
FunctionA(); //same function as in the first exception
}
catch (ExceptionB e)
{
// exception is ExceptionB type
log.Error("At the start something wrong: " + e);
FunctionA(); //same function as in the first exception
}
finally
{
//you can do something here whether there is an exception or not
}
}

关于c# - 在 try block 中尝试 catch - 异常应该调用相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12211286/

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