我编写了一个可能会抛出各种异常的函数。
public class MyClass
{
private void Test(string param)
{
if (param.Length > 10)
throw new ArgumentException();
else if (param.Length > 20)
throw new OverflowException();
else if (string.IsNullOrWhiteSpace(param))
throw new ArgumentException();
else if (param.Length < 1)
throw new FormatException();
}
public void Call(string input)
{
try
{
Test(input);
}
catch (Exception ex)
{
HandleException(ex);
}
}
private void HandleException(Exception ex)
{
//Check if ex is of type ArgumentException
//ToDo..
//Check if ex is of type OverflowException
//ToDo...
//Check if ex is of type ArgumentException
//ToDo..
//Check if ex if of type FormatException
//ToDo..
}
}
是否可以使用 HandleException(ex)私有方法,以便我可以处理所有异常。否则,我必须为每个expcetions编写单独的异常块
答案 0 :(得分:1)
private void HandleException(Exception ex)
{
if (ex is ArgumentException)
{
//ToDo..
}
else if (ex is OverflowException)
{
//ToDo..
}
else if (ex is FormatException)
{
//ToDo..
}
}
如果&#34; is
vs as
&#34;的效果对你来说非常重要,你可以使用这种方法
private void HandleException(Exception ex)
{
ArgumentException argEx;
OverflowException ovfEx;
FormatException fmtEx;
if ((argEx = ex as ArgumentException) != null)
{
//ToDo..
}
else if ((ovfEx = ex as OverflowException) != null)
{
//ToDo..
}
else if ((fmtEx = ex as FormatException) != null)
{
//ToDo..
}
}