【发布时间】:2021-09-16 08:25:36
【问题描述】:
如果有一个方法调用了许多其他方法,并且它们都可以抛出从 ArgumentExceptions 到 EndOfStreamExceptions 的各种异常,最好做一个 catch all 并将其包装在您自己的异常中,然后设置内部异常,或者创建一个基类异常并抛出派生类型。如果抛出违反尽可能重用 BCL 异常的建议的派生类型。比如
public void A()
{
if (someCondition)
{
throw new ArgumentException()
}
}
public void B()
{
if (anotherCondition)
{
throw new InvalidOperation()
}
}
public void C()
{
// Throws format exception
int.Parse(x);
}
public void DoSomething()
{
try
{
A();
B();
C();
}
catch(Exception ex)
{
throw new DoSomethingException("Could not complete DoSomthing"){ InnerException = ex};
}
}
或者做类似的事情会更好
public void DoSomething()
{
A();
B();
C();
D();
}
public void A()
{
if (someCondition)
{
throw new DoSomethingMissingArg()
}
}
public void B()
{
if (anotherCondition)
{
throw new DoSomethingCannotStart()
}
}
public void C()
{
// Throws format exception
if (!int.TryParse(x))
{
throw new DoSomethingFormatException("x must be in y format");
}
}
public class DoSomethingException: Exception
{
}
public class DoSomethingMissingArg: DoSomethingException
{
public DoSomethingMissingArg(){ }
}
public class DoSomethingCannotStart: DoSomethingException
{
public DoSomethingCannotStart(){ }
}
public class DoSomethingFormatException: DoSomethingException
{
public DoSomethingFormatException(){ }
}
【问题讨论】: