一、概念
异常就是Java代码在运行时期发生的问题就是异常。
在Java中,把异常信息封装成了一个类。当出现了问题时,就会创建异常类对象并抛出异常相关的信息(如异常出现的位置、原因等)。
二、分类
错误:指程序在运行期间发生了某种错误(Error),Error错误通常没有具体的处理方式,程序将会结束运行。无法针对处理错误,只能修正错误。
异常:指程序在编译、运行期间发生了某种异常(Exception),我们可以对异常进行具体的处理,若不处理异常,程序将会结束运行。
三、抛出异常
throw关键字:它用来抛出一个指定的异常对象
步骤:1.创建一个异常对象,封装一些提示信息
2.通过throw将异常对象告知调用者
public static int intException (int[] arr) throws Exception{
//是否为空
if (arr==null){
throw new Exception("数组为空");
}
}
四、处理异常
throws:将问题标识出来,报告给调用者,如果方法内通过throw抛出了编译时异常,而没有捕获处理,那么调用者将异常再次抛出给其调用者。
public static void main(String[] args) throws Exception{
int[] arr=null;
int num=intException(arr);
System.out.println(num);
}
public static int intException (int[] arr) throws Exception{
//是否为空
if (arr==null){
throw new Exception("数组为空");
}
int i=(arr.length-1)*2;
return i;
}
try..catch..finally:捕获异常处理
public static void main(String[] args) {
int[] arr={1,2};
//尝试运行代码
try {
getException(arr);
//捕获运行中的异常进行处理
}catch (Exception e) {
System.out.println("有异常");
//一定会执行的代码
}finally{
System.out.println("一定会执行的");
}
五、自定义异常类
自定义异常类NoAgeException:
class NoAgeException extends Exception{
//重写父类构造方法
public NoAgeException() {
super();
}
//重写父类有参构造方法
public NoAgeException(String message) {
super(message);
}
}