异常
指在程序的运行过程中所发生的不正常的事件,它会中断正在运行的程序
异常处理
Java编程语言使用异常处理机制为程序提供了错误处理的能力,Java的异常处理是通过5个关键字来实现的:try、catch、 finally、throw、throws
//使用try-catch块捕获异常,分为三种情况
//第一种情况 :正常
public void method(){
try {
// 代码段(此处不会产生异常)
} catch (异常类型 ex) {
// 对异常进行处理的代码段
}
// 代码段
}
//第二种情况:出现异常
public void method(){
try {
// 代码段 1
// 产生异常的代码段 2
// 代码段 3
} catch (异常类型 ex) {
// 对异常进行处理的代码段4
}
// 代码段5
}
//第三种情况:异常类型不匹配
public void method(){
try {
// 代码段 1
// 产生异常的代码段 2
// 代码段 3
} catch (异常类型 ex) {
// 对异常进行处理的代码段4
}
// 代码段5
}
在catch块中处理异常
加入用户自定义处理信息
调用方法输出异常信息
e.printStackTrace();
异常对象常用的方法
方法 | 说明 |
void printStackTrace() | 输出异常的堆栈信息 |
String getMessage() | 返回异常信息描述字符串, 是printStackTrace()输出信息的一部分 |
常见的异常类型
异常类型 | 说明 |
Exception | 异常层次结构的父类 |
ArithmeticException | 算术错误情形,如以零作除数 |
ArrayIndexOutOfBoundsException | 数组下标越界 |
NullPointerException | 尝试访问 null 对象成员 |
ClassNotFoundException | 不能加载所需的类 |
IllegalArgumentException | 方法接收到非法参数 |
ClassCastException | 对象强制类型转换出错 |
NumberFormatException | 数字格式转换异常,如把"abc"转换成数字 |
在try-catch块后加入finally块
public class Demo03 {
public static void main(String[] args) {
try {
Scanner in = new Scanner(System.in);
System.out.print("请输入被除数:");
int num1 = in.nextInt();
System.out.print("请输入除数:");
int num2 = in.nextInt();
System.out.println(num1 + "/" + num2 + "=" + num1 / num2);
// System.exit(1);//结束虚拟机运行
} catch (Exception e) {
e.printStackTrace();
System.out.println("出现了异常");
System.err.print("除数不能为0");
System.exit(1);//结束虚拟机运行
}finally{
//是否发生异常都执行,除了System.exit(非零整数);
System.out.println("感谢使用本程序!");
}
}
}
存在return的try-catch-finally块
先执行return前的语句,之后在执行finally里的语句,在接着执行return语句
public class Demo01 {
public static void main(String[] args) {
try {
Scanner in = new Scanner(System.in);
System.out.print("请输入被除数:");
int num1 = in.nextInt();
System.out.print("请输入除数:");
int num2 = in.nextInt();
System.out.println(num1 + "/" + num2 + "=" + num1 / num2);
// return;
} catch (Exception e) {
e.printStackTrace();
System.out.println("出现了异常");
System.err.print("除数不能为0");
return;
} finally {
System.out.println("感谢使用本程序!");
}
}
}
多重catch块
引发多种类型的异常
排列catch 语句的顺序:先子类后父类
发生异常时按顺序逐个匹配
只执行第一个与异常类型匹配的catch语句
声明异常
public class Student {
private String name;
private int age;
private String gender;
public Student() {
super();
}
public Student(String name, int age, String gender) {
super();
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) throws Exception {//throws声明异常
if(age>=1&&age<=100){
this.age = age;
}else{
throw new Exception("年龄应该在1-100之间");//throw抛出异常
}
}
public String getGender() {
return gender;
}
public void setGender(String gender) throws Exception {
this.gender = gender;
}
}
throw和throws关键字的区别
throw | throws |
生成并抛出异常 | 声明方法内抛出了异常 |
位于方法体内部,可作为单独语句使用 | 必须跟在方法参数列表后面,不能单独使用 |
抛出一个异常对象,且只能是一个 | 声明抛出异常类型,可以跟多个异常 |