java基础---->Java中异常的使用(二)
2017-05-17 11:39
399 查看
这一篇博客用例子讲述一下异常的处理过程。那些 我们一直惴惴不安 又充满好奇的未来 会在心里隐隐约约地觉得它们是明亮的。
执行的结果如下:
将上述代码result = 9 / 0改为 result = 9 / 2;也就是不产生异常,执行的结果如下:
执行的结果如下:
如果将if(1 + 2 > 2)改变if(1 + 2 > 4),也就是try块里面没有抛出异常。执行的结果如下:
简短的异常说明:
上述代码的运行效果如下:为什么会打印了三次呢?
异常的执行过程
一、实例一:return语句
public class ExceptionTest_1 { public static void main(String[] args) { int result = 0; try { System.out.println("before result"); result = 9 / 0; System.out.println("after result"); } catch (Exception e) { System.out.println("exception" + e.getMessage() + ", result: " + result); return; } finally { System.out.println("final execute, " + result); } System.out.println("out of try statement, " + result); } }
执行的结果如下:
before result exception/ by zero, result: 0 final execute, 0
将上述代码result = 9 / 0改为 result = 9 / 2;也就是不产生异常,执行的结果如下:
before result after result final execute, 4 out of try statement, 4
二、实例二:try里面有try语句
public class ExceptionTest_2 { public static void main(String[] args) { try { if (1 + 2 > 2) { throw new FileNotFoundException(); } try { throw new FileNotFoundException(); } catch (FileNotFoundException e) { System.out.println("world hello"); } } catch (Exception e) { System.out.println("hello world"); } finally { System.out.println("final action"); } } }
执行的结果如下:
hello world final action
如果将if(1 + 2 > 2)改变if(1 + 2 > 4),也就是try块里面没有抛出异常。执行的结果如下:
world hello final action
简短的异常说明:
当抛出异常后,会发生以下的事情。 1、用new在堆上创建异常对象,当前的执行路径被终止,并从当前环境中弹出异常对象的引用。 2、异常处理机制接管程序,并寻找一个恰当的地方继续执行程序。 3、如果有定义了final,那么会执行final块的代码。
三、自定义异常并定义抛错的信息
public class ExceptionTest { @Test public void exception_message_test1() { throw new ValidateRuntimeException("my name is huhx."); // 调用的是getMessage()方法 } } class ValidateRuntimeException extends RuntimeException { public ValidateRuntimeException(String message) { super(message); } @Override public String getMessage() { String message = super.getMessage(); System.out.println("message: " + message); return message + "hello"; } }
上述代码的运行效果如下:为什么会打印了三次呢?
message: my name is huhx. message: my name is huhx. message: my name is huhx. com.linux.huhx.ValidateRuntimeException: my name is huhx.hello at com.linux.huhx.ExceptionTest.exception_message_test1(ExceptionTest.java:12) ........
友情链接
详细的异常说明:http://blog.csdn.net/hguisu/article/details/6155636相关文章推荐
- java基础---->Java中异常的使用(一)
- 程序员_Java基础之<四>-异常
- java 从零开始,学习笔记之基础入门<异常>(十五)
- 【COCOS2D-X 备注篇】ASSETMANAGEREX使用异常解决备注->CHECK_JNI/CC‘JAVA.LANG.NOCLASSDEFFOUNDERROR’
- java基础---->Comparable和Comparator的使用
- Java基础知识强化之集合框架笔记19:List集合迭代器使用之 并发修改异常的产生原因 以及 解决方案
- Java基础--->09.关于JDK使用旧方法编译出错、警告问题。
- <黑马程序员>java基础加强--eclipse的使用
- java 基础异常使用总结
- 我的Java开发学习之旅------>Java使用ObjectOutputStream和ObjectInputStream序列号对象报java.io.EOFException异常的解决方法
- java基础---->java中Properties的使用
- Java基础<六>_异常、包
- Java基础之集合框架——使用堆栈Stack<>对象模拟发牌(TryDeal)
- 黑马程序员 Java基础<四>---> 异常
- java基础<异常>
- 黑马程序员 Java基础<五>异常
- 黑马程序员 java 基础 毕向东 面向对象 异常 以及 package 的使用
- 黑马程序员_Java基础_IO流_字节流,字节流操作文件,缓冲区字节流,流的使用规律,异常记录原理