这篇文章主要介绍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虚拟机:会把异常内容输出控制台
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抓异常,后面没有异常的代码就不会因为前面的代码一些异常而停止,
就可以执行
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());
}
结果:
但是在异常处:还是要添加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("执行中");
}
}
以上是“Java开发过程中异常处理问题的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。