Exception//异常的父类
ArithmeticException//算术异常
NullPointerException//空指针异常
ArrayIndexOutOfBoundsException//下标越界
InputMismatchException//输入不匹配异常
RuntimeExcep//运行是异常
* 1.Throwable是异常的基类,分为Error和Exception,在编程中我们关注Exception
* 2.Exception分为编译期异常和运行期异常
* 3.异常会导致程序中断,无法继续
* 4.在开发中,我们需要把可能出现异常的代码使用try语句块包裹起来
* 5.处理异常可以让程序继续运行
*6.catch可以有好多个,从小到大进行执行
异常处理的语法规则:
第一:try语句不能单独存在,可以和catch,finally组成try....catch...finally、try...catch、try...finally三种结构,catch语句可以有一个或多个,finally最多有一个,他们三个不能单独使用。
第二:try、catch、finally三个代码块中变量的作用域分别独立不能相互访问、
第三:多个catch块时候,java虚拟机会匹配其中一个异常类或其子类,就执行这个catch语句,而不执行其他catch语句
try与catch关键字
在程序中出现异常,就必须进行处理。处理格式如下
try(.....){//JDK1.7以后直接释放资源
//有可能发生异常代码段
}catch(异常类型 对象){
//异常的处理操作
}catch(异常类型 对象){
//异常的处理操作
}....
finally{
//异常的统一出口
}
解决方案:
public class abnormal {
public static void main(String[] args) {
div(10,0);
}
private static void div(int num1,int num2) {
try {
int result=num1/num2;
System.out.println(result);
}catch(ArithmeticException e) {
System.out.println("除数不能为零");
}
System.out.println("程序结束");
}
}
问题描述2:
空指针异常,数组下标越界,除数不能为零
public class abnormal {
public static void main(String[] args) {
div(10,2);
}
private static void div(int num1,int num2) {
int arr[]= {1,2,3,4,5};
System.out.println(arr[5]);
arr=null;
System.out.println(arr.length);
int result=num1/num2;
System.out.println(result);
}
}
解决问题
(1)一旦出生异常,则系统会自动产生一个异常类的实例化对象
(2)此时使用try语句,则会自动匹配一个catch语句执行,如果没有异常处理,则程序退出,并由系统报错
(3)所有的catch根据方法的参数匹配异常的实例化对象,如果匹配成功,则表示由此catch进行处理
public class abnormal {
public static void main(String[] args) {
div(10,2);
}
private static void div(int num1,int num2) {
try {
int arr[]= {1,2,3,4,5};
System.out.println(arr[5]);
arr=null;
System.out.println(arr.length);
int result=num1/num2;
System.out.println(result);
}catch(ArithmeticException e) {
System.out.println("除数不能为零");
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界");
}catch(NullPointerException e) {
System.out.println("空指针异常");
}catch(Exception e) {
System.out.println("出错了");
}
}
}
finally关键字
在进行异常处理之后,在异常的处理格式中还有一个finally语句,那么语句将作为异常的统一出口,不管是否产生了异常,最终都执行此代码
public class abnormal {
public static void main(String[] args) {
method();
}
private static int method() {
int a=10;
int b=5;
try {
System.out.println("a="+a);
System.out.println("b="+b);
int c=a/b;
System.out.println("c="+c);
return c;
}catch(Exception e) {
//代码测试时使用
e.printStackTrace();
}finally {
System.out.println("finally.");
}
return -1;
}
}
结果:
a=10
b=5
c=2
finally.
总结
异常处理的三个关键字try/catch/finally确保了程序出现异常后不会报错而终止程序,让程序可以进行的运行
throw与throws关键字
(1)throws关键字主要在方法的声明上使用,代表方法中不处理异常,而交给调用处处理,实际上对于java程序来说,如果没有加入任何的异常处理,默认由JVM进行异常处理操作。
(2)throw关键字表示在程序中手动抛出一个异常,因为从异常处理机制来看,所有异常一旦产生之后,实际上抛出的就是一个异常类的实例化对象,那么此对象也可以由throw直接抛出
//自动补全alt+/
private static int div2(int a,int b)throws ArithmeticException {
try {
int c=a/b;
return c;
}catch(ArithmeticException e){
throw new ArithmeticException("除数不能为零");
}finally {
System.out.println("程序结束");
}
}
小结:
throw在方法内使用,throws在方法声明中使用