jit*_*arg 0 c# exception-handling try-catch rethrow
我有一些代码捕获异常,回滚事务然后重新抛出异常.
catch ( Exception exSys ) {
bqBusinessQuery.RollBackTransaction();
throw exSys ;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用此代码,VS代码分析会抛出警告说
使用不带参数的'throw',以保留最初引发异常的堆栈位置.
如果我使用代码
catch ( Exception exSys ) {
bqBusinessQuery.RollBackTransaction();
throw;
}
Run Code Online (Sandbox Code Playgroud)
然后我收到警告说
变量'exSys'已声明但从未使用过
我该如何解决这个问题?
编辑 我试过这个方法,但它不起作用.system.exception类需要额外的消息以及内部异常.如果我这样做,它将抛出一条新消息,覆盖原始异常中的消息.我不想得到新的异常,我想用相同的消息抛出相同的异常.
catch (System.Exception ex)
{
throw new System.Exception(ex);
}
Run Code Online (Sandbox Code Playgroud)
编辑
catch (System.Exception ex)
{
throw new System.Exception("Test",ex);
}
Run Code Online (Sandbox Code Playgroud)
尝试过这种方法.然后使用手动导致异常throw new Exception("From inside");.现在,ex.Message返回"Test"而不是"From inside".我希望保留"从内部"消息.这种建议的更改会导致错误显示代码无处不在.:/
您不必将变量绑定到异常:
try
{
...
}
catch (Exception)
{
bqBusinessQuery.RollBackTransaction();
throw;
}
Run Code Online (Sandbox Code Playgroud)
实际上,在您的情况下,当您捕获任何异常时,您甚至不必命名异常类型:
try
{
...
}
catch
{
bqBusinessQuery.RollBackTransaction();
throw;
}
Run Code Online (Sandbox Code Playgroud)
或者(如建议@Zohar Peled)使用捕获的异常作为内部异常抛出一个新异常.这样,您既可以保留堆栈,也可以为异常提供更多上下文.
try
{
...
}
catch (Exception e)
{
throw new Exception("Transaction failed", e);
}
Run Code Online (Sandbox Code Playgroud)
如果您确实想要使用异常进行某些处理(例如记录它),但想要完整地重新抛出它,请声明变量,但使用plain throw:
try
{
...
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
Run Code Online (Sandbox Code Playgroud)
catch (Exception)
{
bqBusinessQuery.RollBackTransaction();
throw;
}
Run Code Online (Sandbox Code Playgroud)
如果您不打算使用异常(例如,将消息传递到某处),则不需要将其拉出到变量中.你可以简单地抓住,做自定义的东西并扔掉.