我可以在课堂上有两个以上的块

时间:2012-11-09 11:06:46

标签: java exception exception-handling try-catch try-catch-finally

我正在开展一个项目,我需要执行两个不同的操作。 我的主控制器方法中有一个finally块。

我的问题是,我最终可以有两个以上,例如:

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

    }

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

所以,有可能吗?

3 个答案:

答案 0 :(得分:7)

每个try / catch / finally语句只能有一个finally子句,但是你可以在同一个方法或多个方法中有多个这样的语句。

基本上,try / catch / finally语句是:

  • try
  • catch(0或更多)
  • finally(0或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
}

答案 1 :(得分:2)

  

我最终可以有两个以上

是的,你可以拥有你想要的try - catch - finally组合,但它们都应该正确格式化。 (即语法应该是正确的)

在您的示例中,您已经编写了正确的语法,并且它将按预期工作。

您可以通过以下方式:

try
{

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

}
finally
{

}

OR

try
{
    try
    {

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

    }
    finally // allowed here too.
    {

    }
}
catch()
{

}
finally
{

}

答案 2 :(得分:-2)

public class Example {

public static void main(String[] args) {
    try{

        try{
            int[] a =new int[5]; 
            a[5]=4;
            }catch (ArrayIndexOutOfBoundsException e)
                            {
               System.out.println("Out Of Range");
            }finally{
                System.out.println("Finally Outof Range Block");
                }

        try{            
            int x=20/0;
            }catch (ArithmeticException e)
                              { 
                                  System.out.println("/by Zero");                                                                            

            }finally{
                System.out.println("FINALLY IN DIVIDES BY ZERO");
                }
    }catch (Exception e) {
        System.out.println("Exception");
    }
    finally{
        System.out.println("FINALLY IN EXCEPTION BLOCK");
    }
    System.out.println("COMPLETED");

     }
}

...