2

2 つの異なる操作を実行する必要があるプロジェクトに取り組んでいます。メインコントローラーメソッドに最終ブロックがあります。

私の質問は、たとえば、最終的に2つ以上持つことができますか?

class test
{
    X()
    {
        try
        {
            //some operations
        }
        finally
        {
            // some essential operation
        }

    }

    //another method
    Y()
    {
        try
        {
            //some operations
        }
        finally
        {
            // some another essential operation
        }
    }
}

それで、それは可能ですか?

4

3 に答える 3

8

try/catch/finally ステートメントごとfinallyに句を 1つだけ持つことができますが、同じメソッドまたは複数のメソッドにそのようなステートメントを複数持つことができます。

基本的に、try/catch/finally ステートメントは次のとおりです。

  • try
  • catch(0以上)
  • finally(0 または 1)

...ただし、少なくとも1 つのcatch/が必要finallyです (「生の」tryステートメントだけを使用することはできません) 。

さらに、ネストすることもできます。

// Acquire resource 1
try {
  // Stuff using resource 1
  // Acquire resource 2
  try {
    // Stuff using resources 1 and 2
  } finally {
    // Release resource 2
  }
} finally {
  // Release resource 1
}
于 2012-11-09T11:08:21.340 に答える
2

最後に2つ以上もらえますか

はい、必要な数のtry - catch - finally組み合わせを使用できますが、すべて正しくフォーマットする必要があります。(つまり、構文は正しいはずです)

あなたの例では、正しい構文を記述しており、期待どおりに機能します。

次の方法で使用できます。

try
{

}
catch() // could be more than one
{

}
finally
{

}

また

try
{
    try
    {

    }
    catch() // more than one catch blocks allowed
    {

    }
    finally // allowed here too.
    {

    }
}
catch()
{

}
finally
{

}
于 2012-11-09T11:10:46.337 に答える