异常的捕获及处理.ppt
上传人:天马****23 上传时间:2024-09-11 格式:PPT 页数:19 大小:1.2MB 金币:10 举报 版权申诉
预览加载中,请您耐心等待几秒...

异常的捕获及处理.ppt

异常的捕获及处理.ppt

预览

免费试读已结束,剩余 9 页请下载文档后查看

10 金币

下载此文档

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

6.1异常简介6.2异常类的继承结构6.3异常处理机制6.4异常处理publicclassExceptionDemo01{publicstaticvoidmain(Stringargs[]){System.out.println("*******计算开始*******");inti=10;intj=0;inttemp=i/j;System.out.println("两个数字相除的结果:"+temp);System.out.println("*******计算结束*******");}}try{可能出现异常的语句;}catch(异常类1异常对象){异常1的处理语句;}catch(异常类2异常对象){异常2的处理语句;}…finally{一定要运行的语句;}publicclassExceptionDemo02{publicstaticvoidmain(Stringargs[]){System.out.println("******计算开始********");inti=10;intj=0;try{inttemp=i/j;//此处产生了异常System.out.println("两个数字相除的结果:"+temp);}catch(ArithmeticExceptionae){System.out.println("出现异常了:"+ae);}System.out.println("*******计算结束*********");}}验证finally的作用:异常的统一出口程序在开发中不会只存在一个异常,肯定会同时存在多个异常。此时就需要使用多个catch语句进行处理。例:使用键盘输入两个数据,进行除法操作。分析:没有输入参数或个数不够——数组超出绑定异常输入的参数不是数字——数字格式化异常除数为零——算术异常……范例ExceptionDemo04.javapublicclassExceptionDemo04{publicstaticvoidmain(Stringargs[]){inti,j;try{Stringstr1=args[0];//接收第一个参数Stringstr2=args[1];//接收第二个参数i=Integer.parseInt(str1);j=Integer.parseInt(str2);inttemp=i/j;//此处产生了异常System.out.println(“相除的结果:”+temp);}catch(ArithmeticExceptione){System.out.println("算术异常:"+e);}catch(NumberFormatExceptione){System.out.println("数字转换异常:"+e);}catch(ArrayIndexOutOfBoundsExceptione){System.out.println("数组越界异常:"+e);}catch(Exceptione){System.out.println("异常:"+e);}System.out.println("******计算结束*****");}}直接打印异常对象System.out.println(e)使用Exception类提供的一个方法printStackTrace()(开发中常用专门打印异常信息)publicclassExceptionDemo05{publicstaticvoidmain(Stringargs[]){System.out.println("******计算开始********");inti=10;intj=0;try{inttemp=i/j;//此处产生了异常System.out.println("相除的结果:"+temp);}catch(Exceptione){e.printStackTrace();}System.out.println("*******计算结束*********");}}4.throw、throwsclassMath{publicintdiv(inti,intj)throwsException{inttemp=i/j;//此处有可能出现异常returntemp;}}publicclassThrowsDemo{publicstaticvoidmain(Stringargs[]){Mathm=n