如果您经常这样做并希望有一个非异常抛出等效项,请尝试:
public static class Catching<TException> where TException : Exception
{
public static bool Try<T>(Func<T> func, out T result)
{
try
{
result = func();
return true;
}
catch (TException x)
{
// log exception message (with call stacks
// and all InnerExceptions)
}
result = default(T);
return false;
}
public static T Try<T>(Func<T> func, T defaultValue)
{
T result;
if (Try(func, out result))
return result;
return defaultValue;
}
}
所以现在你可以这样做了:
Foo.Bar newObj;
if (!Catching<ComException>.Try(() => new Foo.Bar(), out newObj))
{
// didn't work.
}
或者,如果您有一个默认对象存储在 defaultMyInterface 中,如果没有更好的方法,您将使用它来实现接口:
IMyInterface i = Catching<ComException>.Try(() => new Foo.Bar() as IMyInterface,
defaultMyInterface);
您也可以在完全不同的情况下这样做:
int queueSize = Catching<MyParsingException>
.Try(() => Parse(optionStr, "QueueSize"), 5);
如果Parse 抛出MyParsingException,queueSize 将默认为5,否则使用来自Parse 的返回值(或任何其他异常将正常传播,这通常是您想要的意外异常)。
这有助于避免打断代码流,并集中您的日志记录策略。