如何解决处理来自多个方法的异常
我有一个看起来像这样的方法
private void Foo()
{
Method1(var1)
Method2(var1)
Method3(var2)
Method4(var3)
...
//lots of methods in a row like this
}
如何在它调用的每个方法上实现异常处理,而不会到处乱发 try-catch 块?我希望异常消息根据导致异常的方法而有所不同。
示例:Method1()
中断:显示用户 "You don't have permissions for this"
Method2()
中断:显示用户 "File contents are not in the right format"
Method3()
中断:显示用户 "Error at line 3 in file"
等等...
解决方法
一种非常低技术的方法可能只是使用带有通用参数的 Action Delegate 来至少过滤您希望获得的异常
M << N
使用
public void Check<T>(Action action,string errorMessage ) where T : Exception
{
try
{
action();
}
catch (Exception e) when (e is T)
{
ShowMessage(errorMessage);
}
}
不过,我个人认为这是一个相当可疑的解决方案,您可能应该全面重新考虑您的异常处理策略。简而言之,异常不应该用于流量控制,而应该在您确切知道如何处理它们时捕获它们。
此外,方法实现可能应该使用 Try 样式方法(如果它们可用),或者在且仅当它知道期望它们时捕获并处理它们自己的异常。
,您可以做的是创建一个例外列表并将所有例外添加到该列表中。
在系统结束时,您收集所有异常。
以您的情况为例。
private List<Exception> Exceptions = new List<Exception>();
比你做的每个方法都要:
void Method1(string var1)
{
try
{
//some logic
}
catch (Exception e)
{
Exceptions.Add(e);
}
}
您还可以制作自己的错误模型,该模型具有异常属性和其他属性,例如时间、消息等。
要立即显示问题,您可以在全部结束时进行循环,例如:
foreach (var exception in Exceptions)
{
Console.WriteLine(exception.Message);
}
,
您可以在实现这些方法的定义行中的每个方法中抛出您识别的异常,如下所示。
>>> b
0 1
1 2
2 3
3 3
4 3
5 3
6 3
7 3
8 3
9 3
10 3
11 4
12 5
Name: x,dtype: int64
>>> df_out
x x2
2 10 6
3 10 5
4 10 6
5 10 78
6 10 89
7 10 78
8 10 98
9 10 8
10 10 56
然后在 Foo() 方法中编写一个 try 块和相关的 catch 子句,以在代码的一个地方捕获每个异常,如下所示。
public void Method1() throws NoPermissionException{
}
public void Method2() throws IllegalFormatException {
}
public void Method3() throws ArithmeticException{
}
,
如果您根据某些条件(已处理的异常)显式抛出新异常,那么您就不需要通过放置 try-catch 语句到处乱发。
private void Foo()
{
try
{
Method1(var1);
Method2(var1);
Method3(var2);
Method4(var3);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void Method4(object var3)
{
throw new Exception("Exception A");
}
private void Method3(object var2)
{
throw new Exception("Exception B");
}
private void Method2(object var1)
{
throw new Exception("Exception C");
}
private void Method1(object var1)
{
throw new Exception("Exception D");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。