异常和集合
1. 异常 CTRL + 1
1.1 生活中的异常
生病
医生: 你是怎么了?
我: 我难受
医生: 你那里难受
我: 我肚子疼
医生: 怎么回事
我: 周六放纵了一波,吃了一个甜筒
医生: 支付宝消费65元,输液吧
甜筒:
百因必有果,你的报应就是我
1.2 开发中的异常
主要划分为两大类
Error
Exception
统一的父类
Throwable 异常和错误的基类
主要了解的方法:
构造方法 Constructor
Throwable();
创建或者说生成一个异常/错误类对象,异常/错误信息为null
Throwable(String message);
创建或者说生成一个异常/错误类对象,异常/错误信息为message
成员方法:
String toString();
展示当前异常/错误的简要信息
String getMessage();
获取当前异常/错误的信息方法
void printStackTrace();
展示错误/异常的前因后果【红字】
package com.qfedu.a_throwable;
public class Demo1 {
public static void main(String[] args) {
Throwable throwable = new Throwable("急性肠胃炎");
System.out.println(throwable.getMessage());
System.out.println(throwable.toString());
testThrowable();
}
public static void testThrowable() {
new Throwable("测试错误").printStackTrace();
}
}
1.3 异常和错误的区别
Exception
异常 可以处理,代码中也就不存在异常
Error
错误 只能避免
错误和异常根据报错结尾来判断不同的情况。
错误只能避免
异常有两种处理方式
1. 捕获
2. 抛出
1.4 捕获异常
格式:
try {
有可能出现异常的代码
} catch (异常对象) {
对应当前异常处理方式
}
try {
有可能出现异常的代码
} catch (异常对象) {
对应当前异常处理方式
} finally {
用于关闭当前程序使用到的资源。
}
package com.qfedu.a_throwable;
public class Demo3 {
public static void main(String[] args) {
test(20, 0, null);
}
public static void test(int num1, int num2, int[] arr) {
int ret = 0;
try {
arr[0] = 10;
System.out.println("你猜我运行吗???");
ret = num1 / num2;
} catch (ArithmeticException | NullPointerException e) {
System.out.println("都是异常");
} catch (Exception e) {
System.out.println("Exception是所有异常的基类");
}
System.out.println("ret : " + ret);
}
}
1.5 抛出异常
关键字:
throw
在代码中满足条件的情况下,抛出异常
throws
在【方法声明】位置告知调用者,这里有哪些异常抛出
package com.qfedu.a_throwable;
public class Demo4 {
public static void main(String[] args)
throws ArithmeticException, NullPointerException {
try {
test(10, 0, null);
} catch (ArithmeticException | NullPointerException e) {
System.out.println("当前代码存在异常问题");
}
test(10, 0, null);
}
public static void test(int num1, int num2, int[] arr)
throws ArithmeticException, NullPointerException {
if (0 == num2) {
throw new ArithmeticException("算术异常");
}
if (null == arr) {
throw new NullPointerException("数组异常");
}
int ret = num1 / num2;
System.out.println(ret);
}
}
1.6 抛出和捕获使用情况图例
1.7 自定义异常
Java中异常众多!!!
也满足不了我们的日常!!!
单身狗异常
网线断了异常
Java中现有异常无法满足,自定义异常玩一玩了!!!
格式:
class 自定义异常 extends Exception {
// 无参数构造方法
// 有参数构造方法
}
SingleDogException
package com.qfedu.a_throwable;
class SingleDogException extends Exception {
public SingleDogException() {}
public SingleDogException(String message) {
super(message);
}
}
public class Demo5 {
public static void main(String[] args) throws SingleDogException {
try {
buyOneFreeOne(true);
} catch (SingleDogException e) {
System.out.println(e.getMessage());
}
buyOneFreeOne(true);
}
public static void buyOneFreeOne(boolean single) throws SingleDogException {
if (single) {
throw new SingleDogException("路见不平一声吼,大哥没有男朋友");
}
System.out.println("书亦烧仙草买一送一, 美团有券9.9RMB");
}
}