进阶day05-Throwable(异常)里面的三个方法

This commit is contained in:
2026-02-04 14:44:16 +08:00
parent ef8647eea6
commit 4ceb8a4164

View File

@@ -0,0 +1,38 @@
package com.inmind.exception05;
/*
Throwable里面的三个方法
String getMessage() 返回此可抛出的简短描述。
String toString() 返回此throwable的详细消息字符串。
void printStackTrace() 将此throwable的错误信息直接打印在控制台(我们主动打印错误信息)
*/
public class ThrowableDemo10 {
public static void main(String[] args) throws InterruptedException {
try {
int[] arr = {1, 2, 3, 4, 5};
int result = getByIndex(arr, 6);
System.out.println(result);
} catch (ArrayIndexOutOfBoundsException e) {
//String getMessage() 返回此可抛出的简短描述
String message = e.getMessage();
//String toString() 返回此throwable的详细消息字符串
String msg = e.toString();
System.out.println(msg);
System.out.println(e);//打印的底层源码就是在调用e的toString
//void printStackTrace() 将此throwable的错误信息直接打印在控制台(我们主动打印错误信息)
e.printStackTrace();//注意e.printStackTrace()主动打印错误信息操作,是直接在子线程中运行了,这里是多线程的
System.out.println("处理了索引越界异常");
}
System.out.println("程序结束");
}
private static int getByIndex(int[] arr, int index) {
//当传入的索引值不合法时,我们自己主动抛出一个异常,交给调用者处理
if (index < 0 || index > arr.length - 1) {
String msg = "您输入的索引不合法当前数组的索引范围只能是0~"+(arr.length-1)+",但是您输入的索引为"+index;
throw new ArrayIndexOutOfBoundsException(msg);
}
int result = arr[index];//JVM只会创建越界异常
return result;
}
}