簡體   English   中英

C#:“使用”指令和try / catch塊

[英]C#: “using” directive and try/catch block

我知道在數據庫調用的情況下如何使用try / catch塊,並且在使用try / finally構造的上下文中也知道如何使用“ using”指令。

但是,我可以混合使用嗎? 我的意思是,當我使用“ using”指令時,因為我仍然需要處理可能的錯誤,所以我也可以使用try / catch構造嗎?

您絕對可以一起使用。

using塊基本上只是try / finally塊的一點語法糖,並且您可以根據需要嵌套try / finally塊。

using (var foo = ...)
{
     // ...
}

大致相當於:

var foo = ...;
try
{
    // ...
}
finally
{
    foo.Dispose();
}

當然可以做到:

using (var con = new SomeConnection()) {
    try {
        // do some stuff
    }
    catch (SomeException ex) {
        // error handling
    }
}

using是由編譯器翻譯成try..finally ,因此它與將try..catch嵌套在try..finally沒有太大區別。

這是完全正確的:

using (var stream = new MemoryStream())
{
    try
    {
        // Do something with the memory stream
    }
    catch(Exception ex)
    {
        // Do something to handle the exception
    }
}

編譯器會將其轉換為

var stream = new MemoryStream();
try
{
    try
    {
        // Do something with the memory stream
    }
    catch(Exception ex)
    {
        // Do something to handle the exception
    }
}
finally
{
    if (stream != null)
    {
        stream.Dispose();
    }
}

當然,這種嵌套方式也可以相反(例如,在try...catch -block內嵌套using -block)。

一種using例如:

using (var connection = new SqlConnection())
{
    connection.Open
    // do some stuff with the connection
}

只是用於編碼類似以下內容的語法捷徑。

SqlConnection connection = null;
try
{
   connection = new SqlConnection();
   connection.Open
   // do some stuff with the connection
}
finally
{
   if (connection != null)
   {
      connection.Dispose()
   }
}

這意味着,是的,您可以將其與其他try..catch或其他內容混合使用。 就像將try..catch嵌套在try..finally 它只是確保您“使用”的項目超出范圍時被丟棄的快捷方式。 它對您在范圍內所做的操作沒有任何實際限制,包括提供您自己的try..catch異常處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM