首页 技术 正文
技术 2022年11月15日
0 收藏 891 点赞 4,300 浏览 1384 个字

1.异常知识点学习实例

代码如下:

 package fromnet; /**
* 参考链接:https://blog.csdn.net/qq_18505715/article/details/73196421
* @author MSI-Gaming
*
*/ public class ThrowTest1 { // 定义一个方法,抛出 数组越界和算术异常(多个异常 用 "," 隔开)
public void Test1(int x) throws ArrayIndexOutOfBoundsException,ArithmeticException{ System.out.println(x); if(x == 0){ System.out.println("没有异常");
return;
} //数据越界异常
else if (x == 1){ int[] a = new int[3];
a[3] = 5;
} //算术异常
else if (x == 2){ int i = 0;
int j = 5/0;
}
} public static void main(String[] args) { //创建对象
ThrowTest1 object = new ThrowTest1(); // 调用会抛出异常的方法,用try-catch块
try {
object.Test1(0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 数组越界异常
try {
object.Test1(1);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常:"+e);
} // 算术异常
try{ object.Test1(2); }catch(ArithmeticException e){ System.out.println("算术异常:"+e);
} System.out.println("有上面的try-catch后,我才可以来");
//使用 throw 抛出异常(可以抛出异常对象,也可以抛出异常对象的引用)
//这边可去掉try来测试
try{ ArrayIndexOutOfBoundsException exception = new ArrayIndexOutOfBoundsException(); throw exception;//new ArrayIndexOutOfBoundsException();//去掉这一行就是生吞异常了,不报异常 }catch(ArrayIndexOutOfBoundsException e){ System.out.println("thorw抛出异常:"+e);
} } }

2.分析

#在方法Test1()中,如果不抛出异常,即throws。。。,再在main中调用Test1方法object.Test1(1);就会出现ArrayIndexOutOfBoundsException异常情况,并在控制台中能定位到异常位置。

#在main中自定义异常ArrayIndexOutOfBoundsException  exception,并throw。如果没有catch的话,就会在发生异常情况,而catch后,就会处理catch中的处理语句

参考https://blog.csdn.net/qq_18505715/article/details/73196421

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,413
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,186
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905