- 当try中没有遇到异常,会怎么执行?
- 会把try中的代码全部执行,不会执行catch中的代码
- 当try中遇到异常,会怎么执行?
- try中遇到异常后,直接运行catch中的代码
- 如果异常没有被捕获,程序会如何运行?
- 异常没有被捕获时,try...catch...就相当于没有写,由JVM虚拟机默认处理异常
- 同时出现多个异常时,会怎么处理?
- 出现多个异常,可以写多个catch;如果多个异常之间存在子父类关系,则父类一定要写在下面(Exception范围最大,其余的空指针异常、数组索引越界异常等都为子类)
二、throwable的成员方法 1.异常里常见的成员方法:
- public String getMessage() 返回此异常的详细信息字符串
- public String toString() 返回此异常抛出的简短描述
- public void printStackTrace() 把异常的错误信息输出在控制台上
代码示例:
第一个:getMessage:
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3, 4, 5, 6};
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
String message = e.getMessage();
System.out.println(message);
//输出:Index 10 out of bounds for length 6
}
}
第二个:toString
public class exceDemo_04 {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3, 4, 5, 6};
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
String s = e.toString();
System.out.println(s);
//输出:java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
}
}
}
第三个:printStackTrace
public class exceDemo_04 {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3, 4, 5, 6};
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
//输出:java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
// at com.itheima.exception.exceDemo_04.main(exceDemo_04.java:11)
}
}
}
三、自定义异常 1.自定义异常的目的:让异常信息更加清晰,见名知意。



