当前位置 博文首页 > zhouqiyuan1233的博客:Java异常处理
视频连接
异常分类:
JJava会把所有异常当做一个对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类。
在Java API中已经定义了许多异常类,这些异常分为两大类,错误Error和异常Exception
–
Error和Exception的区别:
抛出异常
捕获异常
关键字:
try 、 catch 、 finally 、throw 、 throws
–
try 、catch 这两个关键字是必须的,finally关键字可有可无,主要处理善后工作(例如关闭资源,无论try是否捕获到异常,都会执行finally)
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//try代码块,就是try的监控区
try {
System.out.println(a / b);
} catch (ArithmeticException e) {
//ArithmeticException是要捕获的异常类型,如果在try区域发现异常,并与要捕获的异常相同就执行这个代码块的代码
System.out.println("程序出现异常,0不能作为被除数!!!");
} finally {
//无论程序是否出错,都会执行这里的代码
System.out.println("finally");
}
}
}
捕获的异常类型中 Throwable 是最高的,它可以捕获几乎所有异常
catch 关键字可以使用多次:
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a / b);
} catch (Error e) {
System.out.println("Error");
}catch (Exception e) {
System.out.println("Exception");
}catch (Throwable e) {
System.out.println("Throwable");
} finally {
System.out.println("finally");
}
}
}
注意:如果要一次捕获多个异常,catch后的参数要从上往下从小到大,才能都捕获到到异常:
idea捕获异常代码快速生成:
选中要捕获的代码 Ctrl + Alt + T
throw 一般在方法里使用
public class Demo01 {
public static void main(String[] args) {
new Demo01().test(1,0);
}
public void test(int a,int b){
if (b==0){//主动抛出异常
throw new ArithmeticException();
}
}
}
throws 一般在方法上使用
如果在方法中无法处理这个异常,就交给调用这个方法的方法来处理:
自定义一个异常:
//继承Exception。自定义异常类
public class MyException extends Exception{
//定义一个变量,当这个变量大于10的时候抛出异常
private int detal;
public MyException(int a) {
this.detal=a;
}
//toString打印异常信息
@Override
public String toString() {
return "MyException{" +"数字大于10了。异常,detal=" + detal +'}';
}
}
测试类Test:
public class Test {
static void test(int a) throws MyException {
System.out.println("传递的参数为:" + a);
//如果传递过来的参数大于10就抛出异常
if (a > 10) {
throw new MyException(a);
}
//没有异常就输出 “OK”
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
System.out.println("抛出异常了:"+e);
}
}
}
补充:可以在try catch中的catch后添加一些处理异常的代码
完(Java基础结束)
cs