我的代码当前是
using(var driver = new driver()){something}我希望能够捕获异常。然而,我只想捕捉由"driver = new driver“抛出的异常。通过在线查看,我可以发现如何捕获由整个事件或“某物”抛出的异常,但我不知道如何将try-catch放入"using“参数中。
发布于 2018-01-29 17:57:37
这是一个非常奇怪的要求,但无论你怎么决定。
您应该完全摆脱using,并处理dispose yourself (这会产生相同的结果)。
这就是你想要的:
driver driver = null;
try
{
try
{
driver = new driver();
}
catch(Exception ex)
{
// Here is your specific exception.
}
// Do something
}
finally
{
if(driver != null)
driver.Dispose();
}发布于 2018-01-29 17:56:51
就这么做吧:
Driver driver = null;
try
{
driver = new Driver();
}
catch()
{
// do whatever, throw, fail, return...
}
// if you did not break out of your logic in the catch (why not?)
// add an if(driver != null) before you proceed
using(driver)
{
// something
}发布于 2018-01-29 19:08:49
您可以添加一个方法来构造您的驱动程序,并将try/catch放在其中:
private static Driver CreateDriver()
{
try
{
return new Driver();
}
catch(Exception ex)
{
// whatever other exception handling you want
return null;
}
}
using(var driver = CreateDriver())
{
// something
}当然,如果这样做,当您的something代码在using块内执行时,driver可能为空,因此您需要检查这一点,例如:
using(var driver = CreateDriver())
{
if (driver != null)
{
// something
}
}https://stackoverflow.com/questions/48498357
复制相似问题