//异常是一个对象
//Exception分为运行时异常和非运行时异常
//常见的异常
//算术异常,数组越界异常,类型转换错误异常
//编码时出现频率较高的是:空指针异常
//初学时也有可能遇到:不合理异常
//将容易出现异常的代码放在try中
//出现异常后: 会进入到catch中
public static void demo1() {
try {
int a = 0;
a = 5 / 0;
} catch (Exception e) {
System.out.println("自己捕捉到算数异常");
}
}
//当出现异常后:
//只会中断try中的代码执行,不一向其他位置的代码执行
public static void demo2() {
try {
int a = 0;
a = 5 / 0;
System.out.println("测试会不会走1");
Integer num = null;
num = num + 5;
System.out.println("测试会不会走2");
} catch (Exception e) {
System.out.println("自己捕捉到算数异常");
}
}
//多分支异常
public static void demo3() {
try {
// int a = 0;
// a = 5 / 0;
// System.out.println("测试会不会走1");
Integer num = null;
num = num + 5;
System.out.println("测试会不会走2");
} catch (NullPointerException e) {
System.out.println("自己捕捉到空指针异常");
} catch (ArithmeticException e) {
System.out.println("自己捕捉到算数异常");
}
System.out.println("测试会不会走3");
}
//多分支时,异常的捕捉顺序
//要按照继承关系来捕捉: 子类 -> 父类
//最大的父类要放在最后的catch中
public static void demo4() {
try {
// int a = 0;
// a = 5 / 0;
// System.out.println("测试会不会走1");
Integer num = null;
num = num + 5;
System.out.println("测试会不会走2");
} catch (NullPointerException e) {
System.out.println("自己捕捉到空指针异常");
} catch (ArithmeticException e) {
System.out.println("自己捕捉到算数异常");
} catch (Exception e) {
System.out.println("自己捕捉到算数异常");
}
}
//finally - 不管是否出现异常,都会进入执行
//一般做一些善后的处理工作
//比如文件IO流的close操作等
public static void demo5() {
try {
// int a = 0;
// a = 5 / 0;
// System.out.println("测试会不会走1");
Integer num = null;
num = num + 5;
System.out.println("测试会不会走2");
} catch (NullPointerException e) {
//System.out.println("自己捕捉到空指针异常");
e.printStackTrace();
} catch (ArithmeticException e) {
System.out.println("自己捕捉到算数异常");
} catch (Exception e) {
System.out.println("自己捕捉到算数异常1");
} finally {
System.out.println("不管是否异常都会执行");
}
}
//文件拷贝
public static void demo6() {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream("xxx.txt");
fileOutputStream = new FileOutputStream("yyy.txt");
int b = 0;
while ((b = fileInputStream.read()) != -1) {
fileOutputStream.write(b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fileInputStream) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != fileOutputStream) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//自定义异常(继承)
public static void demo7() {
Car car = new Car();
try {
car.setWheelcuont(5);
} catch (MyException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}