资源描述
实验三 异常处理
一、实验目的
1. 学会利用Try-catch-finally语句来捕获和处理异常;
2. 掌握自定义异常类的方法。
二、实验要求
通过编程理解系统异常处理的机制和创建自定义异常的方法。
三、实验内容
1. 编写使用 try…catch 语句处理异常的程序文件SY4_1.java,源代码如下:
public class SY4_1{
public static void main(String[] arg3) {
System.out.println("这是一个异常处理的例子\n");
try {
int i=10;
i /=0;
}
catch (ArithmeticException e) {
System.out.println("异常是:"+e.getMessage());
}
finally {
System.out.println("finally 语句被执行");
}
}
}
l 编译并运行程序。
注意:如果在 catch 语句中声明的异常类是 Exception,catch 语句也能正确地捕获,这是因为
Exception是ArithmeticException的父类。如果不能确定会发生哪种情况的异常,那么最好指定catch的参数为 Exception,即说明异常的类型为 Exception。
2.编写SY4_2.java 程序,计算两数相除并输出结果。使用两个catch子句,分别捕捉除数为0的异常和参数输入有误异常。源代码如下:
import java.io.*;
class SY4_2{
public static void main(String args[ ]){
try{
BufferedReader strin=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入除数:");
String cl=strin .readLine();
int a=Integer .parseInt(cl);
System .out .print("请输入被除数:");
cl=strin .readLine();
int b=Integer .parseInt(cl);
int c=b/a;
System .out .println("商为:"+c);
}
//捕获与I/O有关的异常
catch(IOException e){e.printStackTrace();}
//捕获数值转化时的异常,如不能将字符转化成数值
catch(NumberFormatException e){
System.out.println("请输入整数!");
//e .printStackTrace();
}
//捕获除数为0的异常
catch(ArithmeticException e){
System .out .println("除数不可以0!");
//e .printstackTrace();
}
}
}
编译并运行,当输入除数为0时,将有异常出现,当输入的不是整数时,如将30输成了3o,出现的是另一种异常。
3.编写程序SY4_3.java,包含自定义异常,当输入数值为13和4时抛出该异常。源代码如下:
class Ex2 extends Exception{
Ex2 (String msg) {
super(msg);
}
}
class SY4_3{
private int x;
void setX(int x) {
this.x=x;
}
void f1() throws Ex2{
if(x==13)
throw new Ex2(“I don’t like 13!”);
else if(x==4)
throw new Ex2(“I don’t like 4!”);
else
system .out.println(100/x);
}
public static void main(Sstring args[ ]) {
SY4_3 a=new SY4_3();
try {
a.steX(5);
//a.setX(13);
//a.setX(4);
//a.setX(0);
a.f1();
}
catch(Ex e) {
Sytem.out.println(“get message:”+e.getMessage());
}
}
编译并运行,分别取消注释上面程序中被注释的语句。当释放a.setX(13)语句后,查看运行结果,当释放a.setX(4)语句后,查看运行结果。
四、实验练习题
1.编写Java程序,创建数组后,对数组访问时发生的数组越界.实验使用try-catch语句处理该异常。运行结果如图所示。
2.自定义一个异常,并将其抛出,异常信息为“这是自定义异常!”。
展开阅读全文