异常
异常定义
异常种类
检查型异常
- 最具代表性的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的,如打开一个不存在的文件;
运行时异常
- 运行时异常时可被程序员规避的异常,与检查性异常相反,运行时异常可以在编译时被忽略;
错误
- 错误不是异常,而是脱离程序员控制的问题,错误在代码中通常被忽略,如栈溢出时,错误发生,而编译也无法检测到;
- ERROR类对象由java虚拟机生成并抛出,大多数代码与代码编写者的操作无关;
异常体系结构
- java把异常当做对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类;
- 在Java API中定义了许多异常类,这些异常分为两类,错误ERROR和异常Exception;
异常处理机制
- 五个关键字:try、catch、finally、throw、throws
- 使用try-catch,程序不会自动停止;
- 普通异常处理
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try{
System.out.println(a/b);
} catch (ArithmeticException e){
System.out.println("程序出现异常,变量b不能为0");
} catch (Error e){
} finally {
System.out.println("finally");
}
}
}
public class Demo02 {
public static void main(String[] args) {
new Demo02().test(1,0);
}
public void test(int a, int b){
if(b==0){
throw new ArithmeticException();
}
}
}
public class Demo02 {
public static void main(String[] args) {
try {
new Demo02().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a, int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();
}
}
}
自定义异常
- 步骤:
- 创建异常类;
- 在方法中通过throw关键字抛出异常对象;
- 如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理,否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常,继续下一步操作;
- 在出现异常方法的调用者中捕获并处理异常;
public class Demo03 {
static void test(int a) throws MyException{
System.out.println("传递的参数为:"+a);
if(a>10)
throw new MyException(a);
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(12);
} catch (Exception e) {
System.out.println("MyException=>"+e);
}
}
}
public class MyException extends Exception {
private int detail;
public MyException(int a) {
this.detail = a;
}
@Override
public String toString() {
return "MyException{" + "="+detail+"}";
}
}
狂神说java b站视频链接