3. 实验基本要求
1. (与上课例子一致)基于员工工资支付的程序(参看实验3),创建一个Employee类的对象数组,数组中的对象引用分别指向不同的子类(Manager、Salesman 和Worker等)对象,通过数组中的对象调用每个子类对象的ComputeSalary()方法,计算每种员工的工资。体验多态为程序带来的灵活性和可维护性。
2. 在一个类中编写4个两数相加的重载方法,参数分别为整整,整实、实整、实实。并在另一个类中编程测试这些方法的运行结果。
3.在程序中主动产生一个ArithmeticException 类型被0 除的异常,并用catch 语句捕获这个异常。最后通过ArithmeticException 类的对象e 的方法getMessage 给出异常的具体类型并显示出来。
4.(选做)下面是一个名称为NegativeAmountException的自定义异常类,表示一个不正常的银行账目事件类。填充下面的语句,完成该类的编写。
class NegativeAmountException _____ ____{
//NegativeAmountException异常:用消息s创建异常 NegativeAmountException(String s){ super(s); } }
class Account{ double balance;
//构造函数,余额为0; public Account(){ balance = 0; }
//构造函数,余额为n,如果初始余额小于0抛出异常
public Account( double n) throws NegativeAmountException{ if(n>0){
this.balance = n; }else {
____________________________________________________; } }
//查询余额方法,返回当前余额 public double getBalance(){ return this.balance; }
//存款方法,存款数额amount; 如果存款数目小于0抛出异常 public void deposit(double amount)____________________{ if(amount>=0){ balance+=amount; }else {
16
throw new NegativeAmountException(\存款出错\); }
}
//取款方法,取款数额amount; 如果取款数目小于0抛出异常 public void withdraw(double amount)____ ________{ if(amount<0){
throw new NegativeAmountException(\操作错误\); }else if(balance
throw new NegativeAmountException(\取款出错\); }else{
balance-=amount; } } }
5. (选做)模仿上题中NegativeAmountException自定义异常的写法,根据下面要求写程序。 自定义异常OnlyOneException与NoOprandException,并补充各自类的构造函数,参数用于保存异常发生时候的信息;添加main方法,从命令行参数读入两个数据,计算这两个数据的和并输出。如果参数的数目只要一个,抛出OnlyOneException异常并退出程序的执行;如果没有参数 ,抛出NoOprandException异常并退出程序的执行。
4. 实验思考题
(1)思考以下程序的运行结果 public class EXP5_2{
public static void main(String[] args) {
System.out.println(“这是一个异常处理的例子\\n”); try {
int i=10; i /=0; }
catch (IndexOutOfBoundsException e) {
System.out.println(\异常是:\ }
finally {
System.out.println(\语句被执行\ } } }
(2)以下程序的运行结果? public class EXP5_3{
public static void main(String[] args) { try {
int a=args.length;
17
System.out.println(\ int b=42/a; int c[]={1}; c[42]=99; }
catch (ArithmeticException e) {
System.out.println(\发生了被 0 除:\ }
catch (ArrayIndexOutOfBoundsException e) { System.out.println(\数组下标越界:\ } } }
(3)以下程序的运行结果? public class EXP5_4 {
static void throwProcess() { try {
throw new NullPointerException(\空指针异常\ }
catch (NullPointerException e) {
System.out.println(\在throwProcess方法中捕获\ throw e; } }
public static void main(String args[]) { try {
throwProcess(); }
catch (NullPointerException e) {
System.out.println(\再次捕获:\ } } }
(4)以下程序的运行结果? public class EXP5_4 {
static void throwProcess() { try {
throw new NullPointerException(\空指针异常\ }
catch (NullPointerException e) {
System.out.println(\在throwProcess方法中捕获\ throw e;
18
} }
public static void main(String args[]) { try {
throwProcess(); }
catch (NullPointerException e) {
System.out.println(\再次捕获:\ } } }
(5)编译运行如下程序,写出程序的运行结果。理解try…catch…finally的使用。
19