JBo*_*one 10 .net c# exception-handling
我一直在编写.NET应用程序,并且对框架中包含的错误处理印象深刻.
当捕获由进程或代码中某处抛出的错误时,我喜欢包含消息(ex.Message通常很常见),还有stacktrace(ex.stacktrace),它有助于将问题追溯到特定位置.
举一个简单的例子,比方说我们正在将数字记录到方法中的日志中:
public void ExampleMethod(int number){
try{
int num = number
...open connection to file
...write number to file
}
catch(Exception ex){
.... deal with exception (ex.message,ex.stacktrace etc...)
}
finally{
...close file connection
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法看到调用的方法(在这种情况下ExampleMethod)与传递的特定数字可能会导致方法调用崩溃?我相信你可以在catch块中记录这个,但我主要感兴趣的是捕获导致系统抛出异常的方法调用和参数.
有任何想法吗?
Chr*_*ter 13
我建议将参数值填充到异常的Data字典中,例如
public void ExampleMethod(int number) {
try {
int num = number
...open connection to file
...write number to file
}
catch(Exception ex) {
ex.Data["number"] = number;
//.... deal with exception (ex.message,ex.stacktrace etc...)
}
finally {
//...close file connection
}
Run Code Online (Sandbox Code Playgroud)
这种方法的另一个优点是你可以填充catch块中的参数,然后重新抛出异常并将其记录到其他地方,而不会丢失堆栈跟踪,例如
catch(Exception ex) {
ex.Data["number"] = number;
throw;
}
Run Code Online (Sandbox Code Playgroud)
如果你想知道方法中参数的值,那么IMO只有一种方法可以做 - 你需要用数据重新打包异常.
例如:
int param1 = 10;
string param2 = "Hello World";
try
{
SomeMethod(param1, param2)
}
catch(SomeExpectedException e)
{
throw new MyParameterSensitiveException(e, param1, param2);
}
Run Code Online (Sandbox Code Playgroud)
您基本上将原始异常重新打包为另一个异常的内部异常,并另外提供用于调用该方法的参数.然后你可以通过某种方式检查出来,找出问题所在.
| 归档时间: |
|
| 查看次数: |
758 次 |
| 最近记录: |