常用Exception类的子类及异常处理实例

常用Exception类的子类及异常处理实例

异常类

描述

NullPointerException

空指针异常

ArrayIndexOutOfBoundsException

数组越界访问异常

IOException

输入\输出异常

NumberFormatException

错误的类型转换异常

ArrayStoreException

当向数组存入错误类型数据时

ClassNotFoundException

试图访问一个根本不存在的类

ArithmeticException

除数为0的算术异常

public class seven{

public static void main(String[] args){

System.out.println("***********计算开始************");

int i=10;

int j=0;

try{

int temp=i/j;

System.out.println("两数相除结果为:+temp");

System.out.println("------------------------");

} //将可能出现异常的代码放入try块中

catch(ArithmeticException e){ //写入除数为零的算术异常

System.out.println("出现异常了:"+e);

} //try块后面必须跟上catch块,用于捕获try语句所产生的异常并做处理

//catch子句的目标是解决"异常"情况,并像没有出错一样继续运行

finally{

System.out.println("不管是否异常都执行此代码");

} //finally块是异常的统一出口,无论有无异常,finally指定的代码都要被执行

//finally块可以省略,省略后程序回跳到try-catch块之后继续执行。

System.out.println("***********计算结果*********");

}

}

相关作品