Java开发过程中异常处理问题的示例分析
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("执行中");
}
}
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















