您的位置:首页 > 编程语言 > Java开发

java 语言程序设计-李尊朝 第9章 异常处理

2013-04-15 15:42 344 查看
异常指程序运行过程中出现的非正常现象。

9.1java异常处理机制

在Java中,将异常情况分为Exception(异常)和Error(错误)两大类。Error类对象由Java虚拟机生成并抛出;Exception类对象由应用程序处理或抛出





异常类的继承结构其中Exception和Error又包含许多子类,exception子类的继承关系ExceptionClassNotFoundExceptionClassNotSupportedExceptionIllegalAccessExceptionInstantiationExceptionInterruptedExceptionNoSuchMethodExceptionRuntimeExceptionArithmeticExceptionArrayStoreExceptionClassCastExceptionIllegalArgumentExceptionIllegalThreadStateExceptionNumberFormatExceptionIllegalMonitorStateExceptionIndexOutOfBoundsExceptionArrayIndexOutOfBoundsExceptionStringIndexOutOfBoundsExceptionNegativeArraySizeExceptionNullPointerExceptionSecurityExceptionException类的主要方法publicException();publicException(Strings);publicStringtoString();publicStringgetMessage();

9.2异常处理方式9.2.1try…catch…finally结构在Java中,可以通过try…catch…finally结构对异常进行捕获和处理,其形式如下:try{可能出现异常的程序代码}catch(异常类名1异常对象名1){异常类名1对应的异常处理代码}catch(异常类名2异常对象名2){异常类名2对应的异常处理代码}┇[finally{必须执行的代码}]说明:1.将可能发生异常的程序代码放置在try程序块中。程序运行过程中,如果该块内的代码没有出现任何异常,后面的各catch块不起任何作用。但如果该块内的代码出现了异常,系统将终止try块代码的执行,自动跳转到所发生的异常类对应的catch块中,执行该块中的代码。2.其中的finally块是个可选项,如果含有finally块,无论异常是否发生,finally块的代码必定执行。3.一个try块可以对应多个catch块,用于对多个异常类进行捕获。但如果它们之间有父子关系,应该将子类的catch块放置在父类catch块之前。例9-1捕获数组下越界异常packageexample9_1; publicclassException1{ publicstaticvoidmain(Stringargs[]){ try{ inta[]={1,2,3,4,5},sum=0; for(inti=0;i<=5;i++) sum=sum+a[i]; System.out.println("sum="+sum); System.out.println("Successfully!"); }catch(ArrayIndexOutOfBoundsExceptione){ System.out.println("ArrayIndexOutOfBoundsExceptiondetected"); }finally{ System.out.println("ProgrammFinished!"); } } }运行结果为:arrayindexoutofboundexceptiondetectedprogramfinished!如果将循环语句中的i<=5改为i<5,那么不会产生异常try块内的所有语句正常执行,但catch块将不执行,最后跳到finally块去执行。例9-2捕获算术异常packageexample9_2; publicclassException2{ publicstaticvoidmain(Stringargs[]){ try{ intx,y; x=15; y=0; System.out.println(x/y); System.out.println("Computingsuccessfully!"); }catch(ArithmeticExceptione){ System.out.println("ArithmeticExceptioncatched!"); System.out.println("Exceptionmessage:"+e.toString()); }finally{ System.out.println("Finallyblock!"); } } }
运行结果为ArithmeticExceptioncatched!Exceptionmessage:java.lang.ArithmeticException:/byzeroFinallyblock!9.2.2抛出异常

通常情况下,异常是由系统自动捕获的。但程序员也可以自己通过throw语句抛出异常。throw语句的格式为:
thrownew异常类名(信息)
其中异常类名为系统异常类名或用户自定义的异常类名,“信息”是可选信息。如果提供了该信息,toString()方法的返回值中将增加该信息内容packageexample9_3; publicclassException3{ publicstaticintSum(intn){ if(n<0) thrownewIllegalArgumentException("n应该为正整数!"); ints=0; for(inti=0;i<=n;i++) s=s+i; returns; } publicstaticvoidmain(Stringargs[]){ try{ intn=Integer.parseInt(args[0]); System.out.println(Sum(n)); }catch(ArrayIndexOutOfBoundsExceptione){ System.out.println("命令行为:"+"javaException3<number>"); }catch(NumberFormatExceptione2){ System.out.println("参数<number>应为整数!"); }catch(IllegalArgumentExceptione3){ System.out.println("错误参数:"+e3.toString()); }finally{ System.out.println("程序结束!"); } } }如果运行该程序的命令输入为javaException3屏幕显示为:命令行为:javaexception3<number>程序结束!如果运行该程序的命令行输入为:javaexception3–4屏幕显示为:错误参数:java.lang.IllegalArgumentException:n应该为正整数!程序结束!2.抛出异常选项
在一些情况下,一个方法并不需要处理它所生成的异常,而是向上传递,由调用该方法的其他方法来捕获该异常,这时就要用到throws子句。
使用格式如下:
返回值类型名方法名([参数表])throws异常类型名
{
声明部分
语句部分
}
例9-4抛出异常的方法publicclassException4{ publicstaticintSum()throwsNegativeArraySizeException{ ints=0; intx[]=newint[-4]; for(inti=0;i<4;i++){ x[i]=i; s=s+x[i]; } returns; } publicstaticvoidmain(Stringargs[]){ try{ System.out.println(Sum()); }catch(NegativeArraySizeExceptione){ System.out.println("异常信息:"+e.toString()); } } }解析:在方法sum()中,初始化数组x时使用了int[-4],将触发NegativeArray-SizeException异常,但sum()方法不对该异常捕获和处理,而希望调用它的方法对该异常捕获和处理,所以在声明方法时,在头部增加了“throwsNegativeArraySzieException”选项,以抛出异常。9.2.3自定义异常类在程序设计过程中,会出现各种各校的问题有些可以通过java系统提供的异常来处理,但还有一引坏能通过java系统的已有类解决。在此情况下,可以自已定义异常类来处理。例9-5自定义异常packageexample9_5; publicclassOverFlowExceptionextendsException{ OverFlowException(){ System.out.println("此处数据有溢出,溢出类是OverFlowException"); } }packageexample9_5;

publicclassException5{

publicstaticintx=100000;
publicstaticintmulti()throwsOverFlowException
{
intaim;
aim=x*x*x;
if(aim>1.0E8||aim<0)
{
thrownewOverFlowException();
}
else
returnx*x;
}
publicstaticvoidmain(Stringargs[])
{
inty;
try
{
y=multi();
System.out.println("y="+y);
}
catch(OverFlowExceptione)
{
System.out.println(e);
}
}
}
解释:OVERFlowException是一个自定义的异常类,其中寂静义了构造方法,其功能是输出信息:此处数据有溢出,溢出类是overflowexception该程序的运行结果如下:些数据有溢出,溢出类是overFlowExceptionOverFlowException例9-6处理多种异常
packageexample9_6;

publicclassMathExceptionextendsException{

MathException()
{
System.out.println("输入数据不正确");
}
}
packageexample9_6;
importjavax.swing.JOptionPane;

publicclassException6{

publicstaticStringname;
publicstaticintpay;
publicstaticvoidinputdata()throwsMathException
{
try
{
name=JOptionPane.showInputDialog("请输入您的姓名");
if(name.equals(""))thrownewException();
//假如没有输入名字就"抛出"一个Exception异常
pay=Integer.parseInt(JOptionPane.showInputDialog("请输入您的月工资"));
if(pay<0)thrownewMathException();
//假如输入的月工资数小于零,就会"抛出"自定义异常mathException
}
catch(Exceptione) //捕获Exception异常
{
System.out.println(e);
System.exit(0);
}
}
publicstaticvoidmain(Stringargs[])
{
try
{
for(inti=1;;i++) //没有给出循环次数限制
{
inputdata();
System.out.println(name+"的年薪是"+pay*12);
}
}
catch(MathExceptionpt) //捕获自定义异常
{
System.out.println(pt);
System.exit(0);
}
}运行程序时,如果为姓名输入一个空串,系统显示:java.lang.Exception如果为姓名输入”zhang”,接着为工资输入”-500”,系统显示:输入数据不正确mathexception如果为姓名输入”zhang”,接着为工资输入”300”,系统显示:zhang的年薪是3600
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐
章节导航