课程表

Groovy课程

工具箱
速查手册

Groovy 异常处理

当前位置:免费教程 » Java相关 » Groovy

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

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

例外大致分为以下类别 -

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

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

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

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

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

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

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

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

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

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

抓取:java.lang.ArrayIndexOutOfBoundsException:5

java.lang.ArrayIndexOutOfBoundsException:5

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

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

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

层次结构异常

捕捉异常

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

  1. try {
  2. //Protected code
  3. } catch(ExceptionName e1) {
  4. //Catch block
  5. }

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

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

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

  1. class Example {
  2. static void main(String[] args) {
  3. try {
  4. def arr = new int[3];
  5. arr[5] = 5;
  6. } catch(Exception ex) {
  7. println("Catching the exception");
  8. }
  9. println("Let's move on after the exception");
  10. }
  11. }

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

  1. Catching the exception
  2. Let's move on after the exception

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

多个捕获块

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

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

  1. class Example {
  2. static void main(String[] args) {
  3. try {
  4. def arr = new int[3];
  5. arr[5] = 5;
  6. }catch(ArrayIndexOutOfBoundsException ex) {
  7. println("Catching the Array out of Bounds exception");
  8. }catch(Exception ex) {
  9. println("Catching the exception");
  10. }
  11. println("Let's move on after the exception");
  12. }
  13. }

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

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

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

finally块

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

使用finally块可以运行任何你想要执行的清除类型语句,无论在受保护代码中发生什么。该块的语法如下。

  1. try {
  2. //Protected code
  3. } catch(ExceptionType1 e1) {
  4. //Catch block
  5. } catch(ExceptionType2 e2) {
  6. //Catch block
  7. } catch(ExceptionType3 e3) {
  8. //Catch block
  9. } finally {
  10. //The finally block always executes.
  11. }

让我们修改我们上面的代码并添加finally代码块。以下是代码段。

  1. class Example {
  2. static void main(String[] args) {
  3. try {
  4. def arr = new int[3];
  5. arr[5] = 5;
  6. } catch(ArrayIndexOutOfBoundsException ex) {
  7. println("Catching the Array out of Bounds exception");
  8. }catch(Exception ex) {
  9. println("Catching the exception");
  10. } finally {
  11. println("The final block");
  12. }
  13. println("Let's move on after the exception");
  14. }
  15. }

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

  1. Catching the Array out of Bounds exception
  2. The final block
  3. Let's move on after the exception

以下是Groovy中提供的异常方法 -

public String getMessage()

返回有关已发生异常的详细消息。此消息在Throwable构造函数中初始化。

public Throwable getCause()

返回由Throwable对象表示的异常原因。

public String toString()

返回与getMessage()的结果连接的类的名称。

public void printStackTrace()

将toString()的结果与堆栈跟踪一起打印到System.err,错误输出流。

public StackTraceElement [] getStackTrace()

返回包含堆栈跟踪上的每个元素的数组。索引0处的元素表示调用堆栈的顶部,数组中的最后一个元素表示调用堆栈底部的方法。

public Throwable fillInStackTrace()

使用当前堆栈跟踪填充此Throwable对象的堆栈跟踪,添加到堆栈跟踪中的任何以前的信息。

例子

下面是使用上面给出的一些方法的代码示例 -

  1. class Example {
  2. static void main(String[] args) {
  3. try {
  4. def arr = new int[3];
  5. arr[5] = 5;
  6. }catch(ArrayIndexOutOfBoundsException ex) {
  7. println(ex.toString());
  8. println(ex.getMessage());
  9. println(ex.getStackTrace());
  10. } catch(Exception ex) {
  11. println("Catching the exception");
  12. }finally {
  13. println("The final block");
  14. }
  15. println("Let's move on after the exception");
  16. }
  17. }

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

  1. java.lang.ArrayIndexOutOfBoundsException: 5
  2. 5
  3. [org.codehaus.groovy.runtime.dgmimpl.arrays.IntegerArrayPutAtMetaMethod$MyPojoMetaMet
  4. hodSite.call(IntegerArrayPutAtMetaMethod.java:75),
  5. org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) ,
  6. org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) ,
  7. org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) ,
  8. Example.main(Sample:8), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),
  9. sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),
  10. sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,
  11. java.lang.reflect.Method.invoke(Method.java:606),
  12. org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93),
  13. groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325),
  14. groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1443),
  15. org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:893),
  16. groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:287),
  17. groovy.lang.GroovyShell.run(GroovyShell.java:524),
  18. groovy.lang.GroovyShell.run(GroovyShell.java:513),
  19. groovy.ui.GroovyMain.processOnce(GroovyMain.java:652),
  20. groovy.ui.GroovyMain.run(GroovyMain.java:384),
  21. groovy.ui.GroovyMain.process(GroovyMain.java:370),
  22. groovy.ui.GroovyMain.processArgs(GroovyMain.java:129),
  23. groovy.ui.GroovyMain.main(GroovyMain.java:109),
  24. sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),
  25. sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),
  26. sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,
  27. java.lang.reflect.Method.invoke(Method.java:606),
  28. org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109),
  29. org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131),
  30. sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),
  31. sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),
  32. sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,
  33. java.lang.reflect.Method.invoke(Method.java:606),
  34. com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)]
  35. The final block
  36. Let's move on after the exception
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号