进阶day05-Throwable(异常)里面的三个方法
This commit is contained in:
38
javaSE-day05/src/com/inmind/exception05/ThrowableDemo10.java
Normal file
38
javaSE-day05/src/com/inmind/exception05/ThrowableDemo10.java
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user