Groovy 异常处理


本文整理自网络,侵删。

任何编程语言都需要异常处理来处理运行时错误,从而可以保持应用程序的正常流程。

异常通常会破坏应用程序的正常流程,这就是为什么我们需要在我们的应用程序中使用异常处理的原因。

例外大致分为以下类别 -

  • 检测异常 -扩展Throwable类(除了RuntimeException和Error)的类称为检查异常egIOException,SQLException等。检查的异常在编译时检查。

一个典型的情况是FileNotFoundException。假设您的应用程序中有以下代码,它从E盘中的文件读取。

class Example {
   static void main(String[] args) {
      File file = new File("E://file.txt");
      FileReader fr = new FileReader(file);
   } 
}

如果文件(file.txt)不在E盘中,那么将引发以下异常。

抓取:java.io.FileNotFoundException:E:\ file.txt(系统找不到指定的文件)。

java.io.FileNotFoundException:E:\ file.txt(系统找不到指定的文件)。

  • 未经检查的异常 -扩展RuntimeException的类称为未检查异常,例如,ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException等。未检查的异常在编译期不检查,而是在运行时检查。

一个典型的情况是ArrayIndexOutOfBoundsException,当您尝试访问大于数组长度的数组的索引时,会发生这种情况。以下是这种错误的典型例子。

class Example {
   static void main(String[] args) {
      def arr = new int[3];
      arr[5] = 5;
   } 
}

当上面的代码执行时,将引发以下异常。

抓取:java.lang.ArrayIndexOutOfBoundsException:5

java.lang.ArrayIndexOutOfBoundsException:5

  • 错误 -错误无法恢复。 OutOfMemoryError,VirtualMachineError,AssertionError等。

这些是程序永远不能恢复的错误,将导致程序崩溃。

下图显示了如何组织Groovy中的异常层次结构。它都基于Java中定义的层次结构。

捕捉异常

方法使用try和catch关键字的组合捕获异常。 try / catch块放置在可能生成异常的代码周围。

try { 
   //Protected code 
} catch(ExceptionName e1) {
   //Catch block 
}

所有可能引发异常的代码都放在受保护的代码块中。

在catch块中,您可以编写自定义代码来处理异常,以便应用程序可以从异常中恢复。

让我们看一个类似的代码示例,我们在上面看到一个索引值大于数组大小的数组。但这次让我们将我们的代码包装在try / catch块中。

class Example {
   static void main(String[] args) {
      try {
         def arr = new int[3];
         arr[5] = 5;
      } catch(Exception ex) {
         println("Catching the exception");
      }
		
      println("Let's move on after the exception");
   }
}

当我们运行上面的程序,我们将得到以下结果 -

Catching the exception 
Let's move on after the exception

从上面的代码,我们在try块中包装错误的代码。在catch块中,我们只是捕获我们的异常并输出一个异常已经发生的消息。

多个捕获块

可以有多个catch块来处理多种类型的异常。对于每个catch块,根据引发的异常的类型,您将编写代码来相应地处理它。

让我们修改上面的代码来具体捕捉ArrayIndexOutOfBoundsException。以下是代码段。

class Example {
   static void main(String[] args) {
      try {
         def arr = new int[3];
         arr[5] = 5;
      }catch(ArrayIndexOutOfBoundsException ex) {
         println("Catching the Array out of Bounds exception");
      }catch(Exception ex) {
         println("Catching the exception");
      }
		
      println("Let's move on after the exception");
   } 
}

当我们运行上面的程序,我们将得到以下结果 -

Catching the Aray out of Bounds exception 
Let's move on after the exception

从上面的代码,你可以看到ArrayIndexOutOfBoundsException catch块首先被捕获,因为它意味着异常的标准。

finally块

finally块跟在try块或catch块之后。代码的finally块总是执行,而不管异常的发生。

阅读剩余部分

相关阅读 >>

Groovy 数据库

Groovy 方法

Groovy 泛型

Groovy 单元测试

Groovy 注释

Groovy jmx

Groovy 元对象编程

Groovy 异常处理

Groovy 正则表达式

Groovy 字符串

更多相关阅读请进入《Groovy》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...