java基础---->Java中异常的使用(二)
2024-08-31 14:02:10
这一篇博客用例子讲述一下异常的处理过程。那些 我们一直惴惴不安 又充满好奇的未来 会在心里隐隐约约地觉得它们是明亮的。
异常的执行过程
一、实例一: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:
final execute,
将上述代码result = 9 / 0改为 result = 9 / 2;也就是不产生异常,执行的结果如下:
before result
after result
final execute,
out of try statement,
二、实例二: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
简短的异常说明:
当抛出异常后,会发生以下的事情。
、用new在堆上创建异常对象,当前的执行路径被终止,并从当前环境中弹出异常对象的引用。
、异常处理机制接管程序,并寻找一个恰当的地方继续执行程序。
、如果有定义了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:)
........
友情链接
最新文章
- Atitit 图像处理 调用opencv 通过java  api   attilax总结
- linux下的ssh工具之,本地上传到linux服务器and Linux服务器文件另存为本地。非sftp工具。
- SHLVL 和 BASH_SUBSHELL 两个变量的区别
- DoTween NGUI bug
- (实用篇)php中计算中文字符串长度、截取中文字符串的函数代码
- UIViewAnimationOptions swift 2
- angularjs kindEditor 中content获得不到值
- 小公司免费的ERP软件
- Combo模糊匹配中文问题
- mui中文在线手册及教程文档
- Bumblebee微服务网关的部署和扩展
- 从.Net到Java学习第十二篇——SpringBoot+JPA提供跨域接口
- sort与uniq命令详解
- 修改css的(屏蔽)overflow: hidden;实现浏览器能把网页全图保存成图片
- NDArray自动求导
- SQLdeveloper同时显示多个表的窗口
- CSS学习总结3:CSS定位
- Elasticsearch集群搭建及使用Java客户端对数据存储和查询
- 建站相关-github+hexo, Markdown
- 20155302 Exp2 后门原理与实践