Java的异常处理
一、什么是异常
程序在执行过程中发生的某些意外,例如:类型错误、内存溢出、文件丢失等,英文名为:Exception
二、异常体系结构
- Java可以把异常当作一个对象来处理,并定义了一个基类 java.lang.Throwable 作为所有异常的超类。
- 在Java API中已经定义了许多异常类,这些异常类分为两大类:错误:Error和异常:Exception。
三、Java异常处理机制
- 关键字:try、catch、finally、throw、throws
- 语法
//若捕获多个异常,需要从小到大进行捕获
try{
//需要被监视的代码块
}catch(Error e){
//捕获错误
//注意:错误不是异常,错误是程序员不可预见的,一般由JVM抛出
}catch(Exception e){
//捕获异常
//Exception与Error都是Throwable的子类,是平级关系,所以类似if语句,按照程序抛出的类型二者只捕获其一
}catch(Throwable e){
//Throwable是Java提供的超类,可捕获任意异常或者错误,相当于对象中的object
}finally{
//善后工作
}
-
快捷键(IDEA)
选中需要被监视的代码块,按住CTRL+ALT+T,自动生成异常捕获处理。
-
代码示例
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try{ //监控区域
int x = a/b;
}catch (ArithmeticException e){ //参数为想要捕获的异常类型
//捕获异常
System.out.println("出现异常");
//打印异常信息
e.printStackTrace();
}finally {//无论是否存在异常,都执行其中语句,用于善后工作,例如:关闭Scanner。可以省略。
System.out.println("处理善后工作");
}
}
}
-
throw 与 throws的区别
throw 用于方法内部抛出,方法内部自己进行处理
throws 用于方法上抛出,交由上一级处理
例:①throw抛出异常
import java.lang.Exception;
public class Test{
public static void main(String[] args) {
int a = 1;
int b = 0;
//throw 抛出异常 division_1
int x = division_1(a,b);
}
static int division_1(int a,int b){
try{ //在方法内部进行监听捕获和处理
if(b==0){
throw new ArithmeticException();
}
}catch(ArithmeticException e){
System.out.println(e.toString());
}
return a/b;
}
}
②throws抛出异常
import java.lang.Exception;
public class Test{
public static void main(String[] args) {
int a = 1;
int b = 0;
//throws 抛出异常
try{ //监控区域
int y = division_2(a,b);
}catch (ArithmeticException e){ //参数为想要捕获的异常类型
//捕获异常
System.out.println("出现异常");
//打印异常信息
e.printStackTrace();
}finally {//无论是否存在异常,都执行其中语句,用于善后工作,例如:关闭Scanner。可以省略。
System.out.println("处理善后工作");
}
}
static int division_2(int a,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException(); //方法发现异常后不进行处理,直接抛到方法外,由调用者进行异常处理
}
return a/b;
}
}
四、自定义异常
有时候 JDK 提供的异常不能满足我们的需要,我们就需要自己定义一个异常。
我们只需要设计一个异常类,继承自Exception即可。
例:
//自定义一个异常,当输入一个大于10的数时,抛出异常
public class Test {
public static void main(String[] args) {
int a = 11;
try{
if(a>10){
//方法内部监听,捕获异常
throw new TestException(a);
}
}catch(TestException e){
System.out.println(e.toString());
}
}
}
//自定义异常
class TestException extends Exception{
//当数值大于10时触法此异常
private int detail;
public TestException(int detail) {
this.detail = detail;
}
@Override
public String toString() {
return "TestException{" +
"detail=" + detail +
'}';
}
}