C# - Try-Catch-Finally on Return

时间:2015-12-22 10:15:50

标签: c# return try-catch

我有以下代码:

private boolean hasMovement() {
    return sensore.getStatoSensore() == 1;
}

private static void waitSecond() {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }
}

public void run() {
    while (true) {
        // Wait until movement noticed
        while (!hasMovement()) {
            waitSecond();
        }
        // Movement noticed, turn light on
        lampada.accendi();

        long lastMovementTime = System.currentTimeMillis();
        // Wait until 10 seconds from last movement
        while (System.currentTimeMillis() < lastMovementTime + (timeoutSpegnimento * 1000)) {
            if (hasMovement()) {
                lastMovementTime = System.currentTimeMillis();
            }
            waitSecond();
        }

        // Turn light off
        lampada.spegni();
    }

这基本上是我在数据库中拥有的活跃用户。但有人可以向我解释,如果成功运行public DataTable GetAllActiveUsers() { DataTable dataTable = new DataTable(); try { connection.Open(); SqlCommand getAllActiveUsersCommand = new SqlCommand(getAllUsers, connection); SqlDataAdapter dataAdapter = new SqlDataAdapter(getAllActiveUsersCommand); dataAdapter.Fill(dataTable); return dataTable; } catch(Exception e) { Console.WriteLine(e); return null; } finally { connection.Close(); } } 块并返回DataTable,是否会执行Finally块吗?

由于

3 个答案:

答案 0 :(得分:8)

如上所述:MSDN

  

通常,当控件离开时,finally块的语句会运行   试试声明。控制的转移可以由于正常而发生   执行,执行休息,继续,转到或返回   语句,或者从try语句中传播异常。

但是最后阻止不是总是执行。你可以阅读Alex Papadimoulis的轶事here

答案 1 :(得分:1)

最后总是执行阻止。

你应该在finally块中处理。因为,配置也会关闭连接并配置非托管内存资源。

finally
{
    connection.Dispose();
}

答案 2 :(得分:0)

是的确如此 无论try {} catch()块中是否存在return语句或抛出异常,都将执行finally块。

相关问题