喵星之旅-成长的雏鹰-java面向对象-6-异常处理

异常

异常是指在程序的运行过程中所发生的不正常的事件,它会中断正在运行的程序。
Java编程语言使用异常处理机制为程序提供了错误处理的能力。

Java中如何进行异常处理

Java的异常处理是通过5个关键字来实现的:try、catch、 finally、throw、throws。

try-catch

使用try-catch块捕获异常,分为三种情况:
第一种情况 :正常(和没有处理的运行是一样的)。
第二种情况:出现异常 (捕获异常,程序继续运行)。
第三种情况:异常类型不匹配(程序终止)。

异常对象常用的方法:
void printStackTrace() 输出异常的堆栈信息
String getMessage() 返回异常信息描述字符串,是printStackTrace()输出信息的一部分

常见的异常类型:
Exception 异常层次结构的父类
ArithmeticException 算术错误情形,如以零作除数
ArrayIndexOutOfBoundsException 数组下标越界
NullPointerException 尝试访问 null 对象成员
ClassNotFoundException 不能加载所需的类
IllegalArgumentException 方法接收到非法参数
ClassCastException 对象强制类型转换出错
NumberFormatException 数字格式转换异常,如把”abc”转换成数字

引发多种类型的异常(多重catch块)
排列catch 语句的顺序:先子类后父类
发生异常时按顺序逐个匹配
只执行第一个与异常类型匹配的catch语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Test3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("请输入被除数:");
try {
int num1 = in.nextInt();
System.out.print("请输入除数:");
int num2 = in.nextInt();
System.out.println(num1+"/"+ num2 +"="+ num1/ num2);
} catch (Exception e) {
System.err.println("出现错误:被除数和除数必须是整数,除数不能为零。");
e.printStackTrace();
}
System.out.println("感谢使用本程序!");
}
}

在try-catch块后加入finally块

1.必须在 try 之后添加 catch 或 finally 块。try 块后可同时接 catch 和 finally 块,但至少有一个块。
2.必须遵循块顺序:若代码同时使用 catch 和 finally 块,则必须将 catch 块放在 try 块之后。
3.catch 块与相应的异常类的类型相关。
4.一个 try 块可能有多个 catch 块。若如此,则执行第一个匹配块。即Java虚拟机会把实际抛出的异常对象依次和各个catch代码块声明的异常类型匹配,如果异常对象为某个异常类型或 其子类的实例,就执行这个catch代码块,不会再执行其他的 catch代码块
5.可嵌套 try-catch-finally 结构。
6.在 try-catch-finally 结构中,可重新抛出异常。
7.除了下列情况,总将执行 finally 做为结束: JVM 过早终止(调用 System.exit(int));在 finally 块中抛出一个未处理的异常;计算机断电、失火、或遭遇病毒攻击。
由此可以看出,catch只会匹配一个,因为只要匹配了一个,虚拟机就会使整个语句退出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Test4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("请输入被除数:");
try {
int num1 = in.nextInt();
System.out.print("请输入除数:");
int num2 = in.nextInt();
System.out.println(num1+"/"+ num2 +"="+ num1/ num2);
} catch (Exception e) {
System.err.println("出现错误:被除数和除数必须是整数,除数不能为零。");
//System.exit(1); // finally语句块不执行的唯一情况
} finally {
System.out.println("感谢使用本程序!");
}
}
}

声明异常

throws声明某个方法可能抛出的各种异常,多个异常用逗号隔开

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Test7 {
/**
* 通过try-catch捕获并处理异常。
* @param args
*/
public static void main(String[] args) {
try {
divide();
} catch (Exception e) {
System.err.println("出现错误:被除数和除数必须是整数,除数不能为零");
e.printStackTrace();
}
}
// /**
// * 通过throws继续声明异常。
// */
// public static void main(String[] args) throws Exception {
// divide();
// }

/**
* 输入被除数和除数,计算商并输出。
* @throws Exception
*/
public static void divide() throws Exception {
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);
}
}


抛出异常

除了系统自动抛出异常外,有些问题需要程序员自行抛出异常。使用throw抛出异常。
throw与throws:
Alt text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Person {
private String name = "";// 姓名
private int age = 0;// 年龄
private String sex = "男";// 性别
/**
* 设置性别。
* @param sex 性别
* @throws Exception
*/
public void setSex(String sex) throws Exception {
if ("男".equals(sex) || "女".equals(sex))
this.sex = sex;
else {
throw new Exception("性别必须是“男”或者“女”!");
}
}
/**
* 打印基本信息。
*/
public void print() {
System.out.println(this.name + "(" + this.sex
+ "," + this.age + "岁)");
}
}


public class Test8 {
public static void main(String[] args) {
Person person = new Person();
try {
person.setSex("Male");
person.print();
} catch (Exception e) {
e.printStackTrace();
}
}
}

异常体系结构

Alt text

自定义异常

当JDK 中的异常类型不能满足程序的需要时,可以自定义异常类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class GenderException extends Exception{
//构造方法1
public GenderException(String message) {
super(message);
}


}



class Person{
private String name=""; //姓名
private int age=0; //年龄
private String sex="男"; //性别
//设置性别
public void setSex(String sex) throws GenderException {
if ("男".equals(sex) || "女".equals(sex))
this.sex = sex;
else {
throw new GenderException("性别必须是“男”或者“女”!");
}
}

//打印基本信息
public void print(){
System.out.println(this.name+"("+this.sex+","+this.age+"岁)");
}
}
public class Test{
public static void main(String[] args){
Person person = new Person();
try {
person.setSex("Male");
person.print();
} catch (GenderException e) {
e.printStackTrace();
}

}
}


文章目录
  1. 异常
  2. Java中如何进行异常处理
    1. try-catch
    2. 在try-catch块后加入finally块
    3. 声明异常
    4. 抛出异常
    5. 异常体系结构
    6. 自定义异常
|