进阶day04-throw关键字的作用

This commit is contained in:
2026-02-04 10:16:25 +08:00
parent 7ee2d948bb
commit a43af9bd28

View File

@@ -0,0 +1,34 @@
package com.inmind.throw02;
/*
Java异常处理的五个关键字try、catch、finally、throw、throws
throw关键字的作用
之前的代码中如果出现异常都是JVM创建并抛出那么能不能自己抛出呢
可以throw能够由java开发人员自己抛出一个异常
语法:throw new 异常名();
为什么要自己抛出异常而不使用JVM的异常操作 呢??
我们要针对指定的异常,做出对应处理方案
*/
public class ThrowDemo03 {
public static void main(String[] args) {
//定义整数数组
int[] arr = {1, 2, 3, 4, 5};
//定义出一个根据索引获取指定数组空间的值
int result = getByIndex(arr,7);
System.out.println(result);
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];
System.out.println("getByIndex方法正常执行");
return result;
}
}