第5章第5章java异常处理课件.ppt
文本预览下载声明
什么是异常? class MyMath{ public int devide(int x,int y){ int result=x/y; return result; } } class MyMathTest{ public static void main(String[] args){ MyMath mobj; mobj=new MyMath(); int result; result=mobj.devide(3,0); System.out.println(the result is + result); } } 该程序编译能通过吗?运行程序,有什么信息返回? 异常 Exception in thread main java.lang.ArithmeticException: / by zero 这说明,程序发生了算术异常(ArithmeticException),非正常的结束了。这种情况就是我们说的异常 异常定义了程序中遇到的非致命的错误,而不是编译时的语法错误。如除数为0,打开一个不存在的文件,操作数越界等等。 异常的基本概念 运行时发生的错误称为异常。 如果不对异常进行处理,那么一旦引发异常,程序将突然中止。 要么控制权返回给操作系统。 要么系统处于死机崩溃状态。 因此,安全健壮的程序设计语言应当引入有效的异常处理机制 对MyMathTest类进行如下修改 class MyMathTest{ public static void main(String[] args){ try{ MyMath mobj; mobj=new MyMath(); int result; result=mobj.devide(3,0); System.out.println(the result is + result); }catch(Exception e){ System.out.println(e.getMessage()); } System.out.println(program is running here.); } } 说明 我们看到,当我们在程序中加了红色的代码后,在出现了异常后,程序没有异常中止,而是正常的继续运行。为什么会这样呢? 我们用try…catch语句对程序中可能出现异常的语句进行了处理 try{ statements }catch(Exception e){ statements } try…catch语句执行过程 try{ MyMath mobj; mobj=new MyMath(); int result; result=mobj.devide(3,0); System.out.println(the result is + result); }catch(Exception e){ System.out.println(e.getMessage()); } System.out.println(program is running here.); catch语句块 当try代码块中的程序发生了异常,系统将这个异常发生的代码行号,类别等信息封装到一个对象中,并将这个对象传递给catch代码块 catch(Exception e){ System.out.println(e.getMessage()); } Exception就是try代码块传递给catch代码块的变量类型,e就是变量名。 问题一:e可以改为其他的名字吗? 编程实践 class NoCatch{ public static void main(String[] args){ String str=args[0]; int i=Integer.parseInt(str); System.out.println(输入的数据为: + i); System.out.println(here is the end of the program); } } 该程序运行时,如果没有输入相应的命令行参数,会怎样? 如何解决? 程序修改如下 class NoCatch{ public static void main(String[] args){ try{ String str=args[0]; int i=Integer.parseInt(str); System.out.println(输入的数据为: + i); }catch(ArrayIndexOutOfBoundsException e){ System.o
显示全部