1.异常:代表程序出现的问题;
Error:系统级别的错误,跟我们无关;
Exception:程序可能出现的问题;
我们通常会用Exception以及它的子类来封装程序出现的问题;
运行时异常:RuntimeException及其子类,编译阶段不出现异常提醒,运行时出现异常,比如数组索引越界异常;
编译时异常:编译阶段就会出现异常提醒;如日期解析异常;作用在于提醒程序员;
2.异常的作用:
- 异常是用来查询bug的关键参考信息;
- 异常可以作为方法内部的一种特殊返回值,以便通知调用者底层的执行情况;
3.异常的处理方式:
JVM虚拟机默认的处理方式:
- 把异常的名称,异常原因及异常出现的位置等信息输出在了控制台;
- 程序停止执行,下面的代码不会再执行了;
4.捕获异常
tr{可能出现异常的代码
}catch(异常类名 变量名){
异常的处理代码
}
目的:当代码出现异常时,可以让程序继续往下执行;
public class StreamDemo8 {
public static void main(String[] args) {
int[] arr={1,2,3,4,5,6};
try{
//可能出现异常的代码
System.out.println(arr[10]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("索引越界了");
}
System.out.println("执行了吗?");
}
}
可以让程序继续执行下去,不停止;
5.异常里三个常见方法:
getMessage();
toString();
printStackTrace();
6.抛出处理
throws:写在方法定义处,表示声明一个异常,告诉调用者,使用本方法可能会有哪些异常;
throw:写在方法内,结束方法,手动抛出异常对象,交给调用者,方法中下面的代码不再执行了;
7.练习
public class GirlFriend {
private String name;
private int age;
public GirlFriend() {
}
public GirlFriend(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
int len=name.length();
if(len<3||len>10){
throw new RuntimeException();
}
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age) {
if(age<18||age>40){
throw new RuntimeException();
}
this.age = age;
}
public String toString() {
return "GirlFriend{name = " + name + ", age = " + age + "}";
}
}
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
//1.键盘录入对象
Scanner sc=new Scanner(System.in);
//2.创建女朋友的对象
GirlFriend gf=new GirlFriend();
while (true) {
//3.接收女朋友的姓名;
try {
System.out.println("请输入你心仪女朋友的名字:");
String name=sc.nextLine();
gf.setName(name);
//4.年龄
System.out.println("请输入你心仪女朋友的年龄:");
String ageStr=sc.nextLine();
int age=Integer.parseInt(ageStr);
gf.setAge(age);
break;
//如果所有的数据都正确,那么跳出循环;
} catch (NumberFormatException e) {
//数字格式化异常;
System.out.println("年龄的格式有误,请重新输入:");
continue;
} catch (RuntimeException e) {
//一定写下面;
System.out.println("姓名的长度或者年龄有误");
continue;
}
}
//5.打印
System.out.println(gf);
}
}
8.自定义异常
- 定义异常类
- 写继承关系
- 空参构造
- 带参构造