要求:
掌握异常的概念以及如何定义、抛出和捕捉处理异常。
实验课前检查预习情况,将程序代码写在作业本上。
内容1:
在定义银行类Bank时,若取钱数大于余额则作为异常处理(InsufficientFundsException)。
思路:产生异常的条件是余额少于取额,因此是否抛出异常要判断条件。
取钱是withdrawal方法中定义的动作,因此在该方法中产生异常。
处理异常安排在调用withdrawal的时候,因此withdrawal方法要声明异常,由上级方法调用。
import java.util.*;
//static int x=100;
class InsufficientFundsException extends Exception {
// double x;
String message;
InsufficientFundsException(int n) {
message = "您的余额不足,无法取出现金";
// System.out.println("您的余额不足,无法取出现金");
}
public String getMessage() {
return message;
}
}
class A {
public void f(int n) throws InsufficientFundsException {
// int x=100;
if (n > 1000) {
InsufficientFundsException ex = new InsufficientFundsException(n);
throw (ex);
} else {
System.out.println("所取金额为:" + n);
System.out.println("剩余金额为:" + (1000 - n));
}
}
}
public class bank {
public static void main(String[] args) {
// TODO Auto-generated method stub
A a = new A();
int m;
Scanner reader = new Scanner(System.in);
System.out.println("输入操作类型:");
m = reader.nextInt();
if (m == 0) {
System.out.println("输入取款金额:");
int money1 = reader.nextInt();
// System.out.println("输入存款金额:");
// int money2=reader.nextInt();
try {
a.f(money1);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
} else if (m == 1) {
System.out.println("输入存款金额:");
int money2 = reader.nextInt();
System.out.println("剩余金额:" + (money2 + 1000));
}
}
}
内容2:
1.定义异常类,当从键盘输入A或a时,抛出自定义异常。
2.程序中捕获异常,查看异常抛出的位置。
3.不捕获异常,将异常往上传递。
import java.io.IOException;
import java.util.*;
class MyException extends Exception {
String m;
MyException() {
m = "出现错误";
}
public String getM() {
return m;
}
}
class B {
public void f(char n) throws MyException {
if (n == 'a' || n == 'A') {
MyException ex = new MyException();
throw (ex);
}
}
}
public class Break {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
char str;
int m;
boolean flag = true;
B b = new B();
Scanner reader = new Scanner(System.in);
System.out.println("输入字符(串)");
// str=(char)System.in.read();
// m='str';
while (flag) {
try {
str = (char) System.in.read();
try {
b.f(str);
} catch (MyException e) {
System.out.println(e.getM());
flag=false;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}