(参考答案版)福建农林大学_java_实验八_异常处理

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Java面向对象程序设计

实验八

异常处理

学号:

姓名:

学院:计算机与信息学院

专业班级:

指导老师:林志伟

2 015.12.3

1 2 .运行结果如下:

caughttheException!!!!

e.getMessage():IthrowanException!!!

.程序源代码如下: packageexperiment.eight;

publicclassMyExceptionTest{

publicstaticvoidmain(String[]args){

inta=1,b=0;

try{

System.out.println(a/b);

} }

catch(ArithmeticExceptione){

System.out.println("ThisisaArithmeticException!(byzero)"); }

}

程序运行结果如下:

ThisisaArithmeticException!(byzero)

.运行结果如下: 3

4 .程序源代码如下:

packageexperiment.eight;

classMyExceptionextendsException{

publicMyException(){

}

publicMyException(Stringmessage){

super(message);

}

staticintMultiply(intn,intm)throwsMyException{

intres=n*m;

if(res>1000)

thrownew MyException("结果res="+res+"超过了"+1000); return res;

}

}

publicclassTestMultiplyException{

publicstaticvoidmain(String[]args){

intn=10,m=200;

try{

System.out.println(MyException.Multiply(n,m));

catch(MyExceptione){

}

System.out.println(e.getMessage());

}

}

}

程序运行结果如下:

结果res=2000超过了1000

.程序源代码如下:

5

packageexperiment.eight;

importjava.util.Scanner;

classMyExceptionextendsException{

publicMyException(){

}

publicMyException(Stringmessage){

super(message);

}

}

classcircle{

staticdoublecalPerimeter(doubler)throwsMyException{

if(r<0.0)

thrownew MyException("不存在半径小于零的圆!!!");

else

return Math.PI*2*r;

}

staticdoublecalArea(doubler)throwsMyException{

if(r<0.0)

thrownew MyException("不存在半径小于零的圆!!!");

else

return Math.PI*r*r;

}

}

publicclassMyCircleExample{

publicstaticvoidmain(String[]args){

Scannerscan=new Scanner(System.in);

doubler=scan.nextDouble();

try{

System.out.println("圆的半径:"+r+"周长:"

+ circle.calPerimeter(r)+"面积:"+circle.calArea(r));

} }

catch(MyExceptione){

System.out.println(e.getMessage());

}

}

程序运行结果如下:

10

圆的半径:10.0周长:62.83185307179586面积:314.1592653589793 -1

不存在半径小于零的圆!!!

6 7 .注释如下:

1)定义这个方法可能会抛出RuntimeException 2)当传入的参数r2为0 时,抛出RuntimeException

3)Finally 内的代码不论是否捕获到异常都一定会运行 .NegativeAmountException 异常类代码如下:

classNegativeAmountExceptionextendsException{

publicNegativeAmountException(){

}

(

( ( publicNegativeAmountException(doubleamout,Stringstr){

System.out.println("Error!!!银行存款数量不能为负:"+amout); System.out.println(str);

}

}

InsufficientFundException 异常类代码如下:

classInsufficientFundExceptionextendsException{

publicInsufficientFundException(){

}

publicInsufficientFundException(doubleamout){

System.out.println("Error!!!银行存款余额不足:"+amout);

}

}

相关文档
最新文档