一.认识异常
异常就是代表程序出现的问题
ctrl+alt+t选择try...catch
二.自定义异常
Java无法为这个世界上全部的问题都提供异常类来处理,如果企业自己的某种问题想通过异常来表示,以便用异常来管理该问题,那就需要自己来定义异常类了
(1)
AgeIllegalRuntimeException.Java
//必须让这个类继承自RuntimeException,才能称为一个运行时异常类
public class AgeIllegalRuntimeException extends RuntimeException{
public AgeIllegalRuntimeException() {
}
public AgeIllegalRuntimeException(String message) {
super(message);
}
}
Test.Java
public class Test3 {
public static void main(String[] args) {
//需求:保存一个合法的年龄
try {
saveAge(160);
System.out.println("底层执行成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("底层出现bug");
}
}
public static void saveAge(int age){
if (age > 0 && age <150){
System.out.println("年龄被保存成功"+age);
}else {
//用一个异常对象封装这个问题
//throw 抛出去这个异常对象
throw new AgeIllegalRuntimeException("/age is illegal,your age is "+age);
}
}
}
(2)
AgeIllegalException.Java
public class AgeIllegalException extends Exception{
public AgeIllegalException() {
}
public AgeIllegalException(String message) {
super(message);
}
}
Test.Java
public class Test3 {
public static void main(String[] args) {
//需求:保存一个合法的年龄
try {
saveAge2(26);
System.out.println("执行成功");
} catch (AgeIllegalException e) {
e.printStackTrace();
System.out.println("出现bug");
}
}
public static void saveAge2(int age) throws AgeIllegalException{
if (age > 0 && age <150){
System.out.println("年龄被保存成功"+age);
}else {
//用一个异常对象封装这个问题
//throw 抛出去这个异常对象
//throws 用在方法上,抛出方法内部的异常
throw new AgeIllegalException("/age is illegal,your age is "+age);
}
}
}
异常的作用:异常是用来查询系统Bug的关键参考信息
异常可以作为方法内部的一种特殊返回值,以便通知上层调用者底层的执行情况
三.异常的处理
(1)
public class Test {
public static void main(String[] args) {
try {
test1();
} catch (Exception e) {
System.out.println("您当前操作有问题");
e.printStackTrace(); // 打印出这个异常对象的信息。记录下来。
}
}
public static void test1() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse("2028-11-11 10:24:11");
System.out.println(d);
test2();
}
public static void test2() throws Exception {
// 读取文件的。
InputStream is = new FileInputStream("D:/meinv.png");
}
}
(2)捕获异常,尝试修复
/**
* 目标:掌握异常的处理方式:捕获异常,尝试修复。
*/
public class Test {
public static void main(String[] args) {
// 需求:调用一个方法,让用户输入一个合适的价格返回为止。
// 尝试修复
while (true) {
try {
System.out.println(getMoney());
break;
} catch (Exception e) {
System.out.println("请您输入合法的数字!!");
}
}
}
public static double getMoney(){
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请您输入合适的价格:");
double money = sc.nextDouble();
if(money >= 0){
return money;
}else {
System.out.println("您输入的价格是不合适的!");
}
}
}
}