1、基本概念
异常处理,是编程语言或计算机硬件里的一种机制,用于处理软件或信息系统中出现的异常状况(即超出程序正常执行流程的某些特殊条件)。
异常处理(又称为错误处理)功能提供了处理程序运行时出现的任何意外或异常情况的方法。异常处理使用 try、catch 和 finally 关键字来尝试可能未成功的操作,处理失败,以及在事后清理资源。
2、异常分类
- Error:jvm系统内部错误,资源耗尽等严重情况;
- Exception:因编程错误或偶然的外在因素导致的情况;
3、异常处理方法
通过异常处理机制处理,可分为:
- 捕获异常:try … catch … catch … … finally;
- 抛出异常:show ; shows;
4、处理方法详解
捕获异常
(1)语法:
try {
… //可能出现的异常
}catch{
}finally{//无条件执行的语句;
}
(2)语法模块作用:
try语句:捕获异常的第一步是用try{…}语句块,选定捕获异常的范围,将可能出现异常的代码放在try语句块中。
catch语句:在catch语句块中是对异常对象进行处理的代码。每个try语句块可以伴随一个或多个catch语句,用于处理可能产生的不同类型的异常对象。
finally语句:(可以不在程序中)在捕获异常中最后一步执行的,不论在try、catch代码块中是否发生了异常事件,finally块中的语句都会被执行;
(3)案例:
//案例一:
public class Erron1 {
public static void main(String[] args) {
int x=0;
try {
System.out.println(2/x);
} catch (Exception e) {
//当不知道捕获的是什么类型的异常时,可以直接使用所有异常的父类Exception
e.printStackTrace();//抛出错误类型,原因,地点
System.out.println(e.getMessage());//输出错误原因
}
}
}
//案例二:
//在try中只要遇到错误就会中断后的语句执行,直接执行catch中的语句;
public class Erron1 {
public static void main(String[] args) {
int x=0;
try {
System.out.println(1);
System.out.println(2/x);//捕捉到异常后就会中断后面语句执行catch中语句
System.out.println(2);
System.out.println(3/x);
} catch (Exception e) {
System.out.println(3);
e.printStackTrace();//抛出错误类型,原因
System.out.println(e.getMessage());//输出错误原因
}
}
//案例三:
//1、只要在tyr中有finally语句finally中的程序就会被执行;
//2、在捕获异常的代码块中(try{}里的代码),如果前面的代码有异常了,就不会执行后面的,也不会执行后面代码扑捉的catch
public class Erron1 {
public static void main(String[] args) {
int x=0;
String[] arr=new String[]{
"e","c","d"};
try {
System.out.println(32/x);
System.out.println(arr[3]);
} catch (ArithmeticException e1) {
e1.printStackTrace();
System.out.println(1);
}catch (ArrayIndexOutOfBoundsException e2) {
e2.printStackTrace();
System.out.println(2);
}finally {
System.out.println("异常处理完成!");
}
System.out.println("OK");
}
}
抛出异常
(1)作用:
产生异常,有调用者处理(在方法声明中用 throws 子句可以声明抛出异常的列表,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类)
(2)throw和throws的区别
-
throw是语句抛出一个异常。
语法:throw (异常对象); -
throws是方法可能抛出异常的声明。(用在声明方法时,表示该方法可能要抛出异常)
语法:(修饰符)(返回值类型)(方法名)([参数列表])[throws(异常类)]{…}
(3)案例:
//案例一:throws
public class Error2 {
public static void main(String[] args) {
A a=new A();
try {
//throws在代码这抛出的异常,在调用方去捕获处理
a.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class A{
int a=12;
public void show() throws NullPointerException{
A b=null;
System.out.println(b.a);
}
}
//案例二:throw
public class Error2 {
public static void main(String[] args) {
B b=new B();
try {
b.age(12);
b.age(-12);
} catch (Exception e) {
e.printStackTrace();//抛出异常
}
}
}
class B{
int age;
public void age(int age) throws Exception {
if (age >=0&&age<+120) {
this.age=age;
System.out.println("年龄是:"+this.age);
}else {
throw new Exception("年龄输入有误!!");//人工抛出异常
}
}
}