Java异常
异常指的是程序执行过程中,导致AVM虚拟机停止工作。
如果程序运行出现异常,JVM一般会做两件事:
1.JVM会根据异常产生的对象的原因创建一个异常对象,这个异常对象包含了内容,地址,原因。
2.在方法中,没有异常逻辑(try…catch),那么JVM就会把异常对象抛出给main方法来处理异常。
异常的处理throw关键字的使用
作用:可以使用throw关键字在指定的方法中抛出异常。
JVM终止正在执行的程序。
/**
*
* @author jianyeli
*/
public class TestThrowable {
public static void main(String[] args) {
int[] arr = null;
int e = getEelement(arr,8);
System.out.println(e);
}
/*
对传递过来的参数数组,进行合法的验证
如果数组传递进来的是Null
那么就抛出指针异常,告知方法调用者是"传递的数组是空的"
*/
public static int getEelement(int[]arr,int index){
if(arr==null){
throw new NullPointerException("数组是空的");
}
int ele = arr[index];
return ele;
}
}
执行结果:
/**
*
* @author jianyeli
*/
public class TestThrowable {
public static void main(String[] args) {
int[] arr = {1,2,2,2,3};
int e = getEelement(arr,8);
System.out.println(e);
}
/*
对传递过来的参数数组,进行合法的验证
如果数组传递进来的是Null
那么就抛出指针异常,告知方法调用者是"传递的数组是空的"
*/
public static int getEelement(int[]arr,int index){
if(arr==null){
throw new NullPointerException("数组是空的");
}
if( index < 0 || index > arr.length-1){
throw new ArrayIndexOutOfBoundsException("超出范围了");
}
int ele = arr[index];
return ele;
}
}
执行结果: