在Java的try、catch和finally块之间可以编写任何语句吗?


不,我们不能在**try、catch和finally块**之间编写任何语句,这些块**构成一个单元**。**try**关键字的功能是识别异常对象,捕获该异常对象,并通过暂停**try块**的执行,将控制权连同识别的异常对象一起转移到**catch块**。**catch块**的功能是接收**try**发送的异常类对象,并捕获该异常类对象,并将该异常类对象赋值给在**catch块**中定义的相应异常类的引用。**finally块**是无论是否发生异常都一定会执行的块。

我们可以编写诸如**try带catch块**、**try带多个catch块**、**try带finally块**和**try带catch和finally块**之类的语句,而不能在这些组合之间编写任何代码或语句。如果尝试在这些块之间放置任何语句,则会抛出**编译时错误**。

语法

try
{
   // Statements to be monitored for exceptions
}
// We can't keep any statements here
catch(Exception ex){
   // Catching the exceptions here
}
// We can't keep any statements here
finally{
   // finally block is optional and can only exist if try or try-catch block is there.
   // This block is always executed whether exception is occurred in the try block or not
   // and occurred exception is caught in the catch block or not.
   // finally block is not executed only for System.exit() and if any Error occurred.
}

示例

在线演示

public class ExceptionHandlingTest {
   public static void main(String[] args) {
      System.out.println("We can keep any number of statements here");
      try {
         int i = 10/0; // This statement throws ArithmeticException
         System.out.println("This statement will not be executed");
      }
      //We can't keep statements here
      catch(ArithmeticException ex){
         System.out.println("This block is executed immediately after an exception is thrown");
      }
      //We can't keep statements here
      finally {
         System.out.println("This block is always executed");
      }
         System.out.println("We can keep any number of statements here");
   }
}

输出

We can keep any number of statements here
This block is executed immediately after an exception is thrown
This block is always executed
We can keep any number of statements here

更新于:2020年2月6日

3K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告