java异常处理-爱代码爱编程
Java异常处理
异常
异常是指在程序的运行过程中所发生的不正常的事件,它会中断正在运行的程序。
Java异常处理关键字
try、catch. finally、throw、throws
捕获异常 | 声明异常 | 抛出异常 | |
---|---|---|---|
try | 执行可能产生异常的代码 | throws | throw |
catch | 捕获异常 | 声明方法可能要抛出的各种异常 | 手动抛出异常 |
finally | 无论是否发生异常,代码总能执行 |
try catch处理异常分为三种情况
- 程序正常执行。
- 出现异常,在catch中找到对应的匹配项,处理并停掉程序。
- 在catch里面的异常不匹配的时候也会停掉程序。
常见的异常类型
异常类型 | 说明 |
---|---|
Exception | 异常层次结构的父类 |
ArithmeticException | 算数错误情形,如以零作为除数 |
ArrayOutOfBoundsException | 数组下标越界 |
NullPointerException | 尝试访问null对象成员 |
ClassNotFoundException | 不能加载所需的类 |
IllgalArgumentException | 无法接收到非法参数 |
ClassCastException | 对象强制类型转换出错 |
NumberFormatException | 数字格式转换异常,比如把"aba"转换为数字 |
try catch异常处理案例:
package unusual;
import java.util.InputMismatchException;
import java.util.Scanner;
import org.junit.Test;
/**
* 测试异常
*
* @author XRY
*
*/
public class TestException {
Scanner scan = new Scanner(System.in);
int numOne;
/**
* 没有用异常处理时
*/
@Test
public void testOne() {
System.out.println("请输入被除数");
if(scan.hasNextInt()) {
int numOne = scan.nextInt();
System.out.println("请输入除数");
int numTwo = scan.nextInt();
System.out.println(String.format("%d / %d = %d", numOne, numTwo, numOne / numTwo));
System.out.println("感谢使用本程序");
}else {
System.out.println("你输入的不是数字!!");
}
}
/**
* 加入try-catch后处理
*/
@Test
public void testTwo() {
try {
System.out.println("请输入被除数。");
int numOne = scan.nextInt();
System.out.println("请输入除数。");
int numTwo = scan.nextInt();
System.out.println(String.format("%d / %d = %d", numOne, numTwo, numOne / numTwo));
//捕获输入不匹配的异常并处理
} catch (InputMismatchException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("输入的不是数字!!");
}catch (ArithmeticException e) {
System.out.println("除数不能为零");
}
System.out.println("感谢使用本程序");
}
}
当在处理异常但不知道怎么判断是什么异常时,可以使用它的父类Exception
package unusual;
import java.util.InputMismatchException;
import java.util.Scanner;
import org.junit.Test;
/**
* 测试异常
*
* @author XRY
*
*/
public class TestException {
Scanner scan = new Scanner(System.in);
int numOne;
/**
* 没有用异常处理时
*/
@Test
public void testOne() {
System.out.println("请输入被除数");
if(scan.hasNextInt()) {
int numOne = scan.nextInt();
System.out.println("请输入除数");
int numTwo = scan.nextInt();
System.out.println(String.format("%d / %d = %d", numOne, numTwo, numOne / numTwo));
System.out.println("感谢使用本程序");
}else {
System.out.println("你输入的不是数字!!");
}
}
/**
* 加入try-catch后处理
*/
@Test
public void testTwo() {
try {
System.out.println("请输入被除数。");
int numOne = scan.nextInt();
System.out.println("请输入除数。");
int numTwo = scan.nextInt();
System.out.println(String.format("%d / %d = %d", numOne, numTwo, numOne / numTwo));
//捕获输入不匹配的异常并处理
// } catch (InputMismatchException e) {
// // TODO Auto-generated catch block
// //e.printStackTrace();
// System.out.println("输入的不是数字!!");
// }catch (ArithmeticException e) {
// System.out.println("除数不能为零");
}catch(Exception e) {
System.out.println("程序出错啦,请联系管理员....");
//不管程序是否出现异常,都会执行finally里面的内容
}finally {
//停止Jvm 1是正常退出, 0是非正常退出
System.exit(1);
System.out.println("感谢使用本程序");
}
}
}
注意:在try-catch中如果含return,还是会执行finally里面的内容。
finally唯一不执行的情况是:
System.exit(1)----强行关闭虚拟机。参数1、0都是可以的,1表示正常退出,0表示非正常退出。
System.exit 被调用后,在虚拟机退出前会执行两个清除任务。
第一,它会执行所有通过 Runtime.addShutdownHook 注册的 shutdown hooks 它能有效的释放JVM之外的资源。
第二,执行清除任务,运行相关的 finalizer 方法终结对象。
自定义异常
当JDK中的异常类型不能满足程序的需要的时候,可以自定义异常类。
使用自定义异常的步骤:
- 定义异常类 :继承Throwable类、继承Exception 或者RuntimeExcept。
- 编写构造方法,继承父类的实现,继承JDK Exception。
- 实例化自定义异常对象。
- 使用throw抛出。
//自定义异常类
package unusual.practice;
public class AgeException extends Exception {
public AgeException(String msg) {
super(msg);
}
}
//实例化自定义异常对象并通过throw抛出异常
package unusual.practice;
/**
* 对年龄进行判断
* @author XRY
*
*/
public class AgeTrow {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException {
//判断年龄,如果在1-100直接赋值,否则抛出异常
if(age < 0 || age >100) {
throw new AgeException("输入的年龄不符!!");
}else {
this.age = age;
}
}
}
//测试自定义异常
package unusual.practice;
import java.util.Scanner;
public class TestAgeException {
public static void main(String[] args) throws AgeException {
AgeTrow ae = new AgeTrow();
Scanner scan = new Scanner(System.in);
System.out.println("请输入你的年龄!");
int num = scan.nextInt();
ae.setAge(num);
System.out.println("你的年龄是" + ae.getAge());
}
}
//输出结果:
请输入你的年龄!
120
Exception in thread "main" unusual.practice.AgeException: 输入的年龄不符!!
at unusual.practice.AgeTrow.setAge(AgeTrow.java:17)
at unusual.practice.TestAgeException.main(TestAgeException.java:11)