回归试试&终于抓住了回归?

时间:2011-08-26 15:49:15

标签: c# try-catch return finally

其中一个有风险吗?一个更好吗?或者它是你打印出来的东西之一,然后投掷飞镖来决定?

我想这样做,因为我明白了最终是如何运作的:

try { 
    stuff that changes something... 
}
catch (System.Exception ex) { 
    something.worked = false; 
    something.err = ex.Message; 
}
finally { 
    stuff.close();
    return something; 
}

但我见过:

try { 
    stuff that changes something...
    return something; 
}
catch (System.Exception ex) { 
    something.worked = false; 
    something.err = ex.Message; 
    return something; 
}
finally { 
    stuff.close(); 
}

3 个答案:

答案 0 :(得分:17)

return你不能finally。您将收到编译器错误:

  

控制不能离开finally子句的主体


如果目标类实现IDisposable,那么接下来我会做:

using (stuff s = new stuff())
{
    return stuff;
}

using (stuff s = new stuff())
{
    try
    {
        // do stuff
        return stuff;
    }
    catch (Exception ex)
    {
        // do logging or another stuff
        return something;
    }
}

如果需要/可能,将为您致电Dispose()

答案 1 :(得分:17)

就我个人而言,我不会这样做,并会使用


try { 
    stuff that changes something... 
}
catch (System.Exception ex) { 
    something.worked = false; 
    something.err = ex.Message; 
}
finally { 
    stuff.close();    
}
return something; 

同样在finally语句中,检查您是否需要关闭/处置对象,因为它们可能从未被打开/设置,如果它们失败了。

另见Is it bad practice to return from within a try catch finally block?

答案 2 :(得分:0)

第二种方法没有风险。但它允许您在异常的情况下返回不同的值。