异常(Exception)是程序在执行过程中所产生的问题。
Java中的异常类都继承Throwable类,Exception异常,可能是编码、环境、用户操作输入出现问题。Error 很少接触。
throws 用于声明一个方法中要抛出的异常
throw 用于抛出异常
public static int intException (int[] arr) throws Exception{
//是否为空
if (arr==null){
throw new Exception("数组为空");
}
}
try cath用于创建被保护的代码,try中有异常发生,相应的cath回去捕获异常
public static void main(String[] args) {
int[] arr={1,2};
//尝试运行代码
try {
getException(arr);
//捕获运行中的异常进行处理
}catch (Exception e) {
System.out.println("有异常");
//一定会执行的代码
}finally{
System.out.println("一定会执行的");
}
自定义异常
class NoAgeException extends Exception{
//重写父类构造方法
public NoAgeException() {
super();
}
//重写父类有参构造方法
public NoAgeException(String message) {
super(message);
}
}
异常分为两种,运行时异常和检查异常,运行时异常时java.lang.RuntimeException类的子类,其他异常都是检查异常