1.异常和错误
在Throable类下面有两个子类:
一个是Error(错误) 一个是Exception(异常)
Error:是代表的JVM本身的错误,咱们程序员是无法通过代码处理的。
Error很少出现但是一,旦出现不可处理的
Exception:异常,代表程序运行过程中程序发生不可预期的事件。可以使用Java
的异常处理机制来处理的。
异常分为两种:
编译时异常: 咱们在写代码的时候显示红色的
运行时异常: 在在运行的时候报错的
数组下标越界 ArrayIndexOutOfBoundsException
空指针异常 NullPointerException
1.1异常的捕捉
语法格式:
try{
//可能出现异常的代码
} catch(异常对象){
//针对于上面异常的处理方案
}
//执行流程: 如果try里面的代码没有出现异常,跳过catch执行下面的代码
//如果try里面的代码出现了异常,会走catch里面的代码
代码是运行时异常
package com.kz.c_four;
public class Demo01 {
public static void main(String[] args) {
try {
int a = 0;
int b = 10;
System.out.println(b/a);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用try catch 包裹
代码是编译时异常 必须修改 不修改无法执行
try{
可能出现的异常代码
} catch (异常对象) {
//当异常出现的时候进行捕捉的代码
} finally {
无论有没有异常都要执行的
}
package com.kz.c_four;
public class Demo01 {
public static void main(String[] args) {
test(2, 0);
}
public static void test (int a, int b) {
int ret = 0;
try {
ret = a / b;
}catch (Exception e) {
//输出异常
e.printStackTrace();
} finally {
System.out.println("报不报错我都要输出");
}
}
}
2异常的抛出
使用两个关键字:
throw:在方法中抛出异常。自己可以抛一个异常
throws:在方法的声明处去写,告知调用者当前有异常
3自定义异常
自定义异常:
随便写一个类去继承Exception 可以使用Exception的所有的方法
以后学习框架的时候,也会写自定义的异常处理器
package com.kz.b_four;
public class Demo02 extends Exception{
public static void main(String[] args) throws Exception{
test(2, 0);
}
//throws 名词 告知调用者当前方法代码有异常
public static void test (int a, int b) throws Exception{
if (b == 0) {
//使用throw抛出一个异常对象 自己造的一个异常
//thorw 抛的动作
throw new Exception("b不能等于0");
}
System.out.println("111");
}
}
注意事项:首先继承Exception 在throw new Exception("b不能等于0");(抛异常)