我正在考虑使用回调而不是在C#/ .NET中抛出异常.
优点是
缺点是
我可能错过了一些关键的缺点,因为我想知道为什么不使用它.我错过了什么缺点?
代替
void ThrowingMethod() {
throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)
和
void CatchingMethod() {
try {
ThrowingMethod();
} catch(Exception e) {
//handle exception
}
}
Run Code Online (Sandbox Code Playgroud)
我会做
void ThrowingMethod(ExceptionHandler exceptionHandler) {
exceptionHandler.handle(new Exception());
}
void CatchingMethod() {
ThrowingMethod(exception => */ handle exception */ );
}
Run Code Online (Sandbox Code Playgroud)
同
delegate void ExceptionHandler(Exception exception);
Run Code Online (Sandbox Code Playgroud)
在某处定义并且"handle(...)"是一个检查null的扩展方法,检索堆栈跟踪,如果在抛出异常时根本没有异常处理程序,则可能抛出"UnhandledException".
void UsedToNotThrowButNowThrowing() {
UsedToNotThrowButNowThrowing(null);
}
//overloads existing method that did not throw to now throw
void UsedToNotThrowButNowThrowing(ExceptionHandler exceptionHandler) {
//extension method "handle" throws an UnhandledException if the handler is null
exceptionHandler.handle(exceptionHandler);
}
Run Code Online (Sandbox Code Playgroud)
TResult ThrowingMethod(ExceptionHandler<TResult> exceptionHandler) {
//code before exception
return exceptionHandler.handle(new Exception()); //return to interrupt execution
//code after exception
}
TResult CatchingMethod() {
return ThrowingMethod(exception => */ handle exception and return value */ );
}
Run Code Online (Sandbox Code Playgroud)
同
delegate TResult ExceptionHandler<TResult>(Exception exception);
Run Code Online (Sandbox Code Playgroud)
一方面,您将需要将这些处理程序传递给应用程序中的几乎每个方法,从而产生开销。这是一个非常重量级的依赖项,也是在构建应用程序之前做出的生死攸关的决定。
其次,存在处理系统引发的异常和来自第三方程序集的其他异常的问题。
第三,异常意味着在抛出时停止程序的执行,因为它确实是“异常”,而不仅仅是可以处理的错误,允许继续执行。
| 归档时间: |
|
| 查看次数: |
520 次 |
| 最近记录: |