异常处理
在Java程序的运行中,通常会遇到两种错误:一种是致命错误,例如,程序运行中内存不足等,这件导致程序不能简单的回复执行;另一种是非致命性错误,例如数组越界等,这种错误通过修正后程序仍然可以继续执行,这种严重的不正常状态,通常称为错误(Error),即异常(Exception)。
- Java中的Throwable类
在Java类库的每个类包中都定义了异常类,所有的异常都直接或间接从Throwable类继承。
Throwable类有两个重要的子类:Error和Exception。
(1)Error一般是指与虚拟机相关的问题,如系统崩溃、虚拟机错误、动态链接失败等。对于这类错误的导致的应用程序中断,程序无法预测和恢复。
(2)Exception则是指一些可以被捕获且可能恢复的异常情况,如 数组越界异常、数字被零除产生的异常、输入/输出异常等。
异常类的构造方法:
public Exception();
public Exception(String s);
异常类中的常用方法:
public String toString() //用来返回描述异常对象信息的字符串。
public String getMessage() //描述当前异常对象的详细信息。
public void printStackTrace()//在屏幕上输出当前异常对象使用的堆栈的轨迹
- 异常处理的方法
(1)程序运行时异常通常不作处理,而由Java虚拟机自动进行处理。
(2)使用try-catch-finally语句捕获异常。
(3)使用子句throw说明抛出异常。
- throw和throws语句
throw语句:
throw语句用来明确地抛出一个“异常”。程序会在throw语句后立即终止,他后面的语句不能执行,然后在包含它所有try块中,从里向外寻找含有语气匹配的catch子句的try块。
实例:
public class ThrowTest1 {
static void demomethod(){
try {
throw new NullPointerException("demo1"); //抛出一个空指针异常
} catch (NullPointerException e) { //该catch块将捕获的异常抛出
System.out.println("caught inside method"); throw e;
}
}
public static void main(String[] args) {
try {
demomethod();
} catch (NullPointerException e) {
System.out.println("caught in main :" +e); //处理被demomenthod()中的catch块抛出的异常
}
}
}
运行结果:
throws语句:
如果一个Java方法遇到不能够处理的情况,那么就可以抛出一个异常。这个方法不仅告诉Java编译器能返回什么值,还可以告诉编译器有可能产生什么错误。如:试图读取文件的方法可能或遇到文件不纯在的情况,那么此时该方法将抛出IOException通知编译器。
实例:
public class ThrowsTest2 {
static void throwsmethod() throws IllegalAccessException{
System.out.println("inside method");
throw new IllegalAccessException("demo2");
}
public static void main(String args[]){
try {
throwsmethod();
} catch (IllegalAccessException e) {
System.out.println("caugth"+e);
}
}
}
运行结果:
- 应用实例
银行取钱业务,当取钱数额大于余额所引发的异常及其处理。
1)自定义的异常类InsufficientFundsException:
public class InsufficientFundsException extends Exception {
private Account excepbank; //定义私有类型的Account类的对象
/**
* 构造方法
*/
public InsufficientFundsException(Account excepbank) {
this.excepbank = excepbank;
}
//显示余额和取钱数目的方法
public String toString() {
String str = "\nInsufficientFundsException:\n 取款失败!您的余额不足。\n当前余额为:"+excepbank.getBalance();
return str;
}
}
2)定义Account类
public class Account {
double balance; //balance用来记载余额
Account(double balance) {
this.balance = balance;
}
public void deposite(double amount){ //存钱
if(amount > 0.0)
balance += amount;
System.out.println("存入"+amount+",当前余额为"+balance);
}
public void withdrawal(double dAmount) throws InsufficientFundsException{ //取钱
if(balance < dAmount){ //余额小于取钱数目,抛出异常
throw new InsufficientFundsException(this); //this指bank本身
}
balance = balance - dAmount;
System.out.println("\n取款成功!\n当前余额:"+balance);
}
public double getBalance() { //获取余额
return balance;
}
}
3)定义一个测试类Test1:
public class Test1{
public static void main(String[] args) {
try {
Account ba = new Account(40);
ba.deposite(300);
ba.withdrawal(333);
ba.withdrawal(50);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
运行结果: