Java开发过程中异常处理问题的示例分析
作者:若安舟已远
时间:2023-04-28
浏览:1
1.运行java时,出现了异常:我这里是因为:arr[3]不存在:java.lang.ArrayIndexOutOfBoundsException:3publicclassbtyf{publicstaticvoidmain(String[]args){int[]arr={1,2,3};System.out.println(arr[0]);System.out.println(arr[3]);System.out.println(arr[1]);//1异常ArrayIndexOutOfBoundsExcep
1.运行java时,出现了异常:
我这里是因为:arr[3]不存在:
java.lang.ArrayIndexOutOfBoundsException: 3
public class btyf {
public static void main(String[] args){
int[] arr={1,2,3};
System.out.println(arr[0]);
System.out.println(arr[3]);
System.out.println(arr[1]);
//1 异常
ArrayIndexOutOfBoundsException 异常名
// btyf.main(btyf.java:13) 异常位置第13行
//
//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
// at btyf.main(btyf.java:13)
}
}结果:

java虚拟机:会把异常内容输出控制台


2.处理异常:

public class btyf {
public static void main(String[] args){
int[] arr={1,2,3};
System.out.println(arr[0]);
try{
System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("你访问的数组索引不存在");
e.printStackTrace(); //输出异常数据:控制台
}
System.out.println(arr[1]);
//1 异常
// ArrayIndexOutOfBoundsException 异常名
// btyf.main(btyf.java:13) 异常位置
//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
// at btyf.main(btyf.java:13)
}
}结果:
通过try抓异常,后面没有异常的代码就不会因为前面的代码一些异常而停止,
就可以执行

3.throwable:成员方法:
System.out.println(e.toString());//打印出异常内容:位置和名称
e.printStackTrace(); //输出异常数据:控制台
System.out.println(e.getMessage()); 一样
多用:System.out.println(e.toString());这个

try{
System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e) {
//System.out.println("你访问的数组索引不存在");
// e.printStackTrace();
System.out.println(e.getMessage());
//public String getMessage() {
// return detailMessage;
// }
System.out.println(e.toString());
}结果:

4.throws:抛出异常:

但是在异常处:还是要添加try catch
添加位置:异常成员方法public static void main(String[] args)throws ArrayIndexOutOfBoundsException{}
代码:
public class uytig {
public static void main(String[] args)throws ArrayIndexOutOfBoundsException{
int[] arr={1,2,3};
System.out.println(arr[0]);
try {
System.out.println(arr[3]);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("执行中");
}
}
作者最新文章
WPS 表格单元格内换行快捷键是什么
2026-10-10 15:48
Word格式转换成PDF?Word转PDF的具体步骤是什么?
2026-09-02 19:13
长安猎手K50 2026款上市,14.19万元起售
2026-08-25 16:08
价格大跳水,网友惊呼买早了!两大巨头正面交锋,最高直降2500元,几乎所有品类“你降我也降”
2026-08-25 16:02
全新奥迪Q3 L申报信息揭晓,车身尺寸升级,动力配置保持强劲
2026-08-25 15:44
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多










































