s-day05--throw关键字的作用
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package com.inmind.exception01;
|
||||
/*
|
||||
Java异常处理的五个关键字:try、catch、finally、throw、throws
|
||||
|
||||
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 result = getValue(arr, 8);
|
||||
System.out.println(result);
|
||||
System.out.println("程序结束");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user