什么是异常 Exception
实际运行中,遇到一些意外情况,例如:用户输入不符合要求,打开文件时文件不存在或者文件格式不对,要读取数据库中的信息,是空的等
异常发生在程序运行期间,影响力正常程序执行,但不至于系统崩溃
简单分类
要理解Java异常1处理是如何工作的,就要掌握以下三种类型:
- 检查性异常:最具代表性的检查性异常是用户错误或问题引起的异常,程序员无法预见
- 运行时异常:运行时异常时可能被程序员避免的异常
- 错误Error:错误不是异常,脱离程序员控制
异常体系结构
- Java把异常当作对象处理,并定义java.lang.Throwable作为异常超类
Exception
在Exception分支中有一个重要的子类RuntimeException(运行时异常)
RuntimeException
- ArrayIndexOutOfBoundsException(数组下标越界)
- NullPointerException(空指针异常)
- ArithmeticException(算术异常)
- MissingRecourceException(丢失资源)
- ClassNotFound(找不到类)
这些异常都是不检查异常,程序中可以选择捕获处理也可以不处理
实例
关键字:try catch finally throw throws
package d0722.exception;
public class Demo01 {
public static void main(String[] args) {
int a=1,b=0;
try{//监控区域
System.out.println(a/b);
}catch (ArithmeticException e){//捕获异常
//catch(想要补充的类型)
System.out.println("除数不能为0");
}catch (Exception e){
System.out.println("Exception");
}catch(Throwable e){
//俩个catch层层递进关系,范围越来越大
System.out.println("Throwable");
}finally {//善后
System.out.println("finally");
}
//finally可以不要,finally一般包括Io,资源关闭
}
}
package d0722.exception;
public class Demo02 {
public static void main(String[] args) {
int a=1,b=0;
//Ctrl+Alt+T自动生成捕获异常
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();//打印错误的栈信息
} finally {
}
}
}
package d0722.exception;
public class Demo03 {
public static void main(String[] args) {
int a=1,b=0;
try{
test(a,b);
}catch(Exception e){
System.out.println("Exception");
}
}
//throw、throws一般用在方法中
public static void test (int a,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();
}
}
}
自定义异常
自定义异常类:
package d0722.exception;
//自定义异常
public class MyException extends Exception{
private int detail;
public MyException(int detail) {
this.detail = detail;
}
//异常打印信息
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
测试类
package d0722.exception;
public class Test {
public static void main(String[] args) {
int a=11;
try {
test(a);
} catch (MyException e) {
System.out.println(e);
}
}
public static void test(int a)throws MyException{
if(a>10)
throw new MyException(a);
}
}
运行结果:
MyException{detail=11}