s-day05-throw关键字的作用
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package com.inmind.exception01;
|
||||
/*
|
||||
throw关键字的作用
|
||||
之前的代码中如果出现异常都是JVM创建并抛出的,那么我们能不能自己抛出异常呢???
|
||||
可以,throw能够让java开发人员自己抛出一个异常。
|
||||
语法:throw new 异常名();
|
||||
|
||||
为何要自己抛出异常,而不使用JVM的异常操作呢????
|
||||
1.自己抛出的异常,是根据具体的业务进行操作
|
||||
2.JVM会直接终止程序。
|
||||
|
||||
*/
|
||||
public class ThrowDemo03 {
|
||||
public static void main(String[] args) {
|
||||
int[] arr = {1, 2, 3, 4, 5};
|
||||
//调用一个方法,获取数组指定索引的值
|
||||
int value = getValue(arr,10);
|
||||
System.out.println(value);
|
||||
System.out.println("程序结束");
|
||||
}
|
||||
|
||||
private static int getValue(int[] arr, int index) {
|
||||
//此处可能发生越界异常,我们能不能自己抛出异常,通知调用者呢???可以使用throw关键字
|
||||
if (index < 0 || index >= arr.length) {
|
||||
//自己抛异常
|
||||
String msg = "当前数组的最大索引为:"+(arr.length-1)+",它的合法的索引范围只能是0~"+(arr.length-1);
|
||||
throw new ArrayIndexOutOfBoundsException(msg);
|
||||
}
|
||||
int value = arr[index];
|
||||
return value;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user