异常
一、是什么
代表程序出现的问题
二、异常的分类
error:错误
exception:异常,通常用它和它的子类封装程序出现的问题。
运行时异常RuntimeException及其子类,编译时不会出现异常,运行时出现。
其他异常:编译时出现。
自定义异常:控制台报错见名知意
1定义异常类
2写继承关系
运行时:由于参数错误导致
编译时:提醒程序员检查本地信息
3空参构造
4带参构造
public class NameFormatException extends RuntimeException {
public NameFormatException(){
}
public NameFormatException(Stirng message){
super(message);
}
}
三、异常的作用
1、查看bug的关键参考信息。
2、作为方法内部的特殊返回值,通知调用者底层执行情况。
四、异常的处理方式
1、JVM默认处理方式
把异常的名称,异常原因,异常出现的位置等信息输出在控制台
程序停止执行,异常之下的代码不执行
2、自己处理
try{
可能出现异常的代码
} catch (异常类名 变量) {
处理
}
//出现异常后代码继续执行
int[] arr = {1,2,3};
try {
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("索引越界了 ");
}
System.out.println("看看我执行了吗");
1try没遇到问题
将try中所有代码执行完,不会执行catch的代码
2try遇到多个问题
解决遇到的第一个问题;
多个catch与之对应;
注意:
捕获多个异常,异常存在父子关系,父类需要写在最下面。
3try遇到问题但没被捕获,
白写,被虚拟机处理
4try遇到问题,try下面的代码怎么做
遇到问题,直接跳转至catch,若没有与之匹配,被虚拟机处理
Throwable public String getMessage() 返回详细消息的字符串 public String toString() 简短描述 public void printStackTrace() 异常错误信息返回控制台
int[] arr = {1,2,3};
try {
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
String message = e.getMessage();
System.out.println(message);
}
int[] arr = {1,2,3};
try {
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
String str =e.toString();
System.out.println(str);
}
int[] arr = {1,2,3};
try {
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
//
java.lang.ArrayIndexOutOfBoundsException: 10
at com.study.myexception.ExceptionDemo2.main(ExceptionDemo2.java:7)
3、抛出异常
throws 写在方法定义出,表示声明一个异常 告诉调用者使用本方法可能会有哪些异常 编译时异常:必须写 throw 写在方法内部,手动抛出异常对象 交给调用者,方法下面的代码不执行
1522

被折叠的 条评论
为什么被折叠?



