异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的。
比如说,你的代码少了一个分号,那么运行出来结果是提示是错误java.lang.error;如果你用system.out.println(11/0),那么你是因为你用0做了除数,会抛出java.lang.arithmeticexception的异常。
异常发生的原因有很多,通常包含以下几大类:
用户输入了非法数据。
要打开的文件不存在。
网络通信时连接中断,或者jvm内存溢出。
这些异常有的是因为用户错误引起,有的是程序错误引起的,还有其它一些是因为物理错误引起的。-
要理解java异常处理是如何工作的,你需要掌握以下三种类型的异常:
检查性异常:最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的。例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略。
运行时异常: 运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略。
错误: 错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。
所有的异常类是从java.lang.exception类继承的子类。
exception类是throwable类的子类。除了exception类外,throwable还有一个子类error 。
java程序通常不捕获错误。错误一般发生在严重故障时,它们在java程序处理的范畴之外。
error用来指示运行时环境发生的错误。
例如,jvm内存溢出。一般地,程序不会从错误中恢复。
异常类有两个主要的子类:ioexception类和runtimeexception类。
在java 内置类中(接下来会说明),有大部分常用检查性和非检查性异常。
java 语言定义了一些异常类在java.lang标准包中。
标准运行时异常类的子类是最常见的异常类。由于java.lang包是默认加载到所有的java程序的,所以大部分从运行时异常类继承而来的异常都可以直接使用。
java根据各个类库也定义了一些其他的异常,下面的表中列出了java的非检查性异常。
异常 | 描述 |
---|---|
arithmeticexception | 当出现异常的运算条件时,抛出此异常。例如,一个整数"除以零"时,抛出此类的一个实例。 |
arrayindexoutofboundsexception | 用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引。 |
arraystoreexception | 试图将错误类型的对象存储到一个对象数组时抛出的异常。 |
classcastexception | 当试图将对象强制转换为不是实例的子类时,抛出该异常。 |
illegalargumentexception | 抛出的异常表明向方法传递了一个不合法或不正确的参数。 |
illegalmonitorstateexception | 抛出的异常表明某一线程已经试图等待对象的监视器,或者试图通知其他正在等待对象的监视器而本身没有指定监视器的线程。 |
illegalstateexception | 在非法或不适当的时间调用方法时产生的信号。换句话说,即 java 环境或 java 应用程序没有处于请求操作所要求的适当状态下。 |
illegalthreadstateexception | 线程没有处于请求操作所要求的适当状态时抛出的异常。 |
indexoutofboundsexception | 指示某排序索引(例如对数组、字符串或向量的排序)超出范围时抛出。 |
negativearraysizeexception | 如果应用程序试图创建大小为负的数组,则抛出该异常。 |
nullpointerexception | 当应用程序试图在需要对象的地方使用 null 时,抛出该异常 |
numberformatexception | 当应用程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常。 |
securityexception | 由安全管理器抛出的异常,指示存在安全侵犯。 |
stringindexoutofboundsexception | 此异常由 string 方法抛出,指示索引或者为负,或者超出字符串的大小。 |
unsupportedoperationexception | 当不支持请求的操作时,抛出该异常。 |
下面的表中列出了java定义在java.lang包中的检查性异常类。
异常 | 描述 |
---|---|
classnotfoundexception | 应用程序试图加载类时,找不到相应的类,抛出该异常。 |
clonenotsupportedexception | 当调用 object 类中的 clone 方法克隆对象,但该对象的类无法实现 cloneable 接口时,抛出该异常。 |
illegalaccessexception | 拒绝访问一个类的时候,抛出该异常。 |
instantiationexception | 当试图使用 class 类中的 newinstance 方法创建一个类的实例,而指定的类对象因为是一个接口或是一个抽象类而无法实例化时,抛出该异常。 |
interruptedexception | 一个线程被另一个线程中断,抛出该异常。 |
nosuchfieldexception | 请求的变量不存在 |
nosuchmethodexception | 请求的方法不存在 |
下面的列表是throwable 类的主要方法:
序号 | 方法及说明 |
---|---|
1 | public string getmessage() 返回关于发生的异常的详细信息。这个消息在throwable 类的构造函数中初始化了。 |
2 | public throwable getcause() 返回一个throwable 对象代表异常原因。 |
3 | public string tostring() 使用getmessage()的结果返回类的串级名字。 |
4 | public void printstacktrace() 打印tostring()结果和栈层次到system.err,即错误输出流。 |
5 | public stacktraceelement [] getstacktrace() 返回一个包含堆栈层次的数组。下标为0的元素代表栈顶,最后一个元素代表方法调用堆栈的栈底。 |
6 | public throwable fillinstacktrace() 用当前的调用栈层次填充throwable 对象栈层次,添加到栈层次任何先前信息中。 |
使用try和catch关键字可以捕获异常。try/catch代码块放在异常可能发生的地方。
try/catch代码块中的代码称为保护代码,使用 try/catch的语法如下:
try
{
// 程序代码
}catch(exceptionname e1)
{
//catch 块
}
catch语句包含要捕获异常类型的声明。当保护代码块中发生一个异常时,try后面的catch块就会被检查。
如果发生的异常包含在catch块中,异常会被传递到该catch块,这和传递一个参数到方法是一样。
下面的例子中声明有两个元素的一个数组,当代码试图访问数组的第三个元素的时候就会抛出一个异常。
// 文件名 : exceptest.java
import java.io.*;
public class exceptest{
public static void main(string args[]){
try{
int a[] = new int[2];
system.out.println("access element three :" + a[3]);
}catch(arrayindexoutofboundsexception e){
system.out.println("exception thrown :" + e);
}
system.out.println("out of the block");
}
}
以上代码编译运行输出结果如下:
exception thrown :java.lang.arrayindexoutofboundsexception: 3
out of the block
一个try代码块后面跟随多个catch代码块的情况就叫多重捕获。
多重捕获块的语法如下所示:
try{
// 程序代码
}catch(异常类型1 异常的变量名1){
// 程序代码
}catch(异常类型2 异常的变量名2){
// 程序代码
}catch(异常类型2 异常的变量名2){
// 程序代码
}
上面的代码段包含了3个catch块。
可以在try语句后面添加任意数量的catch块。
如果保护代码中发生异常,异常被抛给第一个catch块。
如果抛出异常的数据类型与exceptiontype1匹配,它在这里就会被捕获。
如果不匹配,它会被传递给第二个catch块。
如此,直到异常被捕获或者通过所有的catch块。
该实例展示了怎么使用多重try/catch。
try
{
file = new fileinputstream(filename);
x = (byte) file.read();
}catch(ioexception i)
{
i.printstacktrace();
return -1;
}catch(filenotfoundexception f) //not valid!
{
f.printstacktrace();
return -1;
}
如果一个方法没有捕获一个检查性异常,那么该方法必须使用throws 关键字来声明。throws关键字放在方法签名的尾部。
也可以使用throw关键字抛出一个异常,无论它是新实例化的还是刚捕获到的。
下面方法的声明抛出一个remoteexception异常:
import java.io.*;
public class classname
{
public void deposit(double amount) throws remoteexception
{
// method implementation
throw new remoteexception();
}
//remainder of class definition
}
一个方法可以声明抛出多个异常,多个异常之间用逗号隔开。
例如,下面的方法声明抛出remoteexception和insufficientfundsexception:
import java.io.*;
public class classname
{
public void withdraw(double amount) throws remoteexception,
insufficientfundsexception
{
// method implementation
}
//remainder of class definition
}
finally关键字用来创建在try代码块后面执行的代码块。
无论是否发生异常,finally代码块中的代码总会被执行。
在finally代码块中,可以运行清理类型等收尾善后性质的语句。
finally代码块出现在catch代码块最后,语法如下:
try{
// 程序代码
}catch(异常类型1 异常的变量名1){
// 程序代码
}catch(异常类型2 异常的变量名2){
// 程序代码
}finally{
// 程序代码
}
public class exceptest{
public static void main(string args[]){
int a[] = new int[2];
try{
system.out.println("access element three :" + a[3]);
}catch(arrayindexoutofboundsexception e){
system.out.println("exception thrown :" + e);
}
finally{
a[0] = 6;
system.out.println("first element value: " +a[0]);
system.out.println("the finally statement is executed");
}
}
}
以上实例编译运行结果如下:
exception thrown :java.lang.arrayindexoutofboundsexception: 3
first element value: 6
the finally statement is executed
注意下面事项:
catch不能独立于try存在。
在try/catch后面添加finally块并非强制性要求的。
try代码后不能既没catch块也没finally块。
try, catch, finally块之间不能添加任何代码。
在java中你可以自定义异常。编写自己的异常类时需要记住下面的几点。
所有异常都必须是throwable的子类。
如果希望写一个检查性异常类,则需要继承exception类。
如果你想写一个运行时异常类,那么需要继承runtimeexception 类。
可以像下面这样定义自己的异常类:
class myexception extends exception{
}
只继承exception 类来创建的异常类是检查性异常类。
下面的insufficientfundsexception类是用户定义的异常类,它继承自exception。
一个异常类和其它任何类一样,包含有变量和方法。
// 文件名insufficientfundsexception.java
import java.io.*;
public class insufficientfundsexception extends exception
{
private double amount;
public insufficientfundsexception(double amount)
{
this.amount = amount;
}
public double getamount()
{
return amount;
}
}
为了展示如何使用我们自定义的异常类,
在下面的checkingaccount 类中包含一个withdraw()方法抛出一个insufficientfundsexception异常。
// 文件名称 checkingaccount.java
import java.io.*;
public class checkingaccount
{
private double balance;
private int number;
public checkingaccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
insufficientfundsexception
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new insufficientfundsexception(needs);
}
}
public double getbalance()
{
return balance;
}
public int getnumber()
{
return number;
}
}
下面的bankdemo程序示范了如何调用checkingaccount类的deposit() 和withdraw()方法。
//文件名称 bankdemo.java
public class bankdemo
{
public static void main(string [] args)
{
checkingaccount c = new checkingaccount(101);
system.out.println("depositing $500...");
c.deposit(500.00);
try
{
system.out.println("\nwithdrawing $100...");
c.withdraw(100.00);
system.out.println("\nwithdrawing $600...");
c.withdraw(600.00);
}catch(insufficientfundsexception e)
{
system.out.println("sorry, but you are short $"
+ e.getamount());
e.printstacktrace();
}
}
}
编译上面三个文件,并运行程序bankdemo,得到结果如下所示:
depositing $500...
withdrawing $100...
withdrawing $600...
sorry, but you are short $200.0
insufficientfundsexception
at checkingaccount.withdraw(checkingaccount.java:25)
at bankdemo.main(bankdemo.java:13)
在java中定义了两种类型的异常和错误。
jvm(java虚拟机)异常:由jvm抛出的异常或错误。例如:nullpointerexception类,arrayindexoutofboundsexception类,classcastexception类。
程序级异常:由程序或者api程序抛出的异常。例如illegalargumentexception类,illegalstateexception类。
学习完本教程,建议您进行实战练习来巩固您新学到的知识:点击进入实战