s-day05--Throwable里面的三个方法

This commit is contained in:
xx
2026-10-16 14:57:05 +08:00
parent 2b42607714
commit 9df0a91256
@@ -0,0 +1,45 @@
package com.inmind.exception01;
/*
13.Throwable里面的三个方法
String getMessage() 返回此可抛出的简短描述。
String toString() 返回此throwable的详细消息字符串。
void printStackTrace() 将此throwable的错误信息直接打印在控制台(我们主动打印错误信息)
*/
public class Demo10 {
public static void main(String[] args) throws Exception{
try {
System.out.println("try的代码-------开始了【1】");
int[] arr = {1, 2, 3, 4, 5};
int result = getValue(arr, 8);
System.out.println("try的代码-------结束了【2】");
//将真正的异常对象,赋值给 e,ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException(msg);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("----------------------");
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();//将异常的信息由我们主动地打印到控制来查看,不是JVM异常终止的情况。异常信息的打印是多线程的,所以,不是依次运行
System.out.println("----------------------");
System.out.println("捕获了异常---【3】");
System.out.println("处理了数组索引越界异常");
}finally {
System.out.println("finally中的代码执行了-----【4】");
}
Thread.sleep(10);
System.out.println("程序结束---【5】");
}
private static int getValue(int[] arr, int index) {
//先判断索引是否规范,不规范则主动自己抛出一个越界异常
if (index < 0 || index >= arr.length) {
String msg = "数组的最大索引为:"+(arr.length-1)+",当前索引"+index+",是不合法的";
throw new ArrayIndexOutOfBoundsException(msg);//程序自己抛出异常而不是jvm
}
int result = arr[index];//ArrayIndexOutOfBoundsException
return result;
}
}