1,异常
异常的定义:就是程序在运行时出现不正常情况。
对于严重的异常:Java通过Error类进行描述。对于Error一般不编写针对性的代码对其进行处理。
对于非严重的异常:Java通过Exception类进行描述。对于Exception可以使用针对性的处理方式进行处理。
2,运用Java的异常处理机制
Java提供两种异常处理机制
(1)用try...catch语句捕获并且处理异常;
(2)使用throw抛出异常,异常必须是java.lang.Throwable类的对象或者该类的子类的对象;
(3)使用throws声明方法抛出异常;
(4)使用finally语句声明在任何情况下都会执行的代码。
3,try...catch的用法:
try{
需要被检测的代码;
}
catch(异常类 变量){
处理异常的代码;(处理方式)
}
finally{
一定会执行的语句;
}
(1)try不能脱离catch或者finally而单独存在;
(2)try后面可以跟0个或者多个catch,还可以有至多0个或者多个finally;
(3)try后面可以只跟finally代码块;
(4)在try代码块中定义的变量的作用域只能够用于try代码块, 在catch代码块和finally代码块中不能够访问该变量;
(5)当try代码块后面跟若干个catch块时,JVM会一次匹配异常情况,如果抛出的异常类型是catch处理异常类型或者是其子类型,则执行相应的catch代码块,之后的catch块不会再执行;
(6)如果一个方法可能抛出受检查异常,要么使用try...catch进行捕获和处理,或者使用throws声明抛出异常;
4,throw和throws的区别:
(1)throws使用在函数上,throw使用在函数内;
(2)throws后面跟的异常类,可以跟多个,用逗号隔开;throw后跟的是异常对象;
throws抛出异常交给调用该方法的方法处理,即:
public class Test {
public static void main(String[] args) {
Test2 test2 = new Test2();
try {
System.out.println("invoke the method begin!");
test2.method();
System.out.println("invoke the method end!");
} catch (Exception e) {
System.out.println("catch Exception!");
}
}
}
class Test2 {
public void method() throws Exception {
System.out.println("method begin!");
int a = 10;
int b = 0;
int c = a / b;
System.out.println("method end!");
}
}
运行结果:
invoke the method begin!
method begin!
catch Exception!
throw语句抛出异常。throw后的语句没有机会执行。
public class Test {
public static void main(String[] args) {
Test2 test2 = new Test2();
try {
System.out.println("invoke the method begin!");
test2.method();
System.out.println("invoke the method end!");
} catch (Exception e) {
System.out.println("catch Exception!");
}
}
}
class Test2 {
public void method() {
System.out.println("method begin!");
throw new ArrayIndexOutOfBoundsException();
}
}
运行结果:
invoke the method begin!
method begin!
catch Exception!
5,创建自己的异常
class FuShuException extends Exception{//自定义异常
private int value;
public FuShuException(String msg,int value) {
super(msg);
this.value = value;
}
public int getValue(){
return value;
}
}
class Demo{
int div(int a,int b)throws FuShuException{
if(b<0)
throw new FuShuException("出现了除数是负数的情况 / by fushu",b);//手动通过throw关键字抛出一个自定义异常对象。
return a/b;
}
}
public class ExceptionDemo1 {
public static void main(String[] args) {
Demo d = new Demo();
try {
int x = d.div(5, -1);
} catch (FuShuException e) {
System.out.println(e.getMessage());
System.out.println("错误的负数是:"+e.getValue());
}
}
}
运行结果:
出现了除数是负数的情况 / by fushu
错误的负数是:-1
6,.受检查异常和运行时异常
(1)运行时异常
抛出一个异常(throw 一个异常的对象)没有用try...catch捕获并处理,也没有用throws进行声明,这样的错误在编译时并不会检查出来,在运行时才会出现运行时的异常。
(2)受检查异常
除了运行时异常,其他异常均是受检查异常,特点是如果throw一个异常对象,如果没有使用try...catch捕获并处理,并且没有使用throws对异常进行声明,则会出现编译错误。
Java中常见的运行时异常:IllegalArgumentException(无效参数异常)、ClassCastException(数据类型转换错误)、IndexOutOfBoundException(下角标越界异常)、NullPointerException(空指针异常)、ArithmeticException(算术异常)。