异常处理机制有其二
其一:
try-catch-finally
try{
… //可能产生异常的代码
}
catch( ExceptionName1 e ){
… //当产生ExceptionName1型异常时的处置措施
}
catch( ExceptionName2 e ){
… //当产生ExceptionName2型异常时的处置措施
}[ finally{
… //无论是否发生异常,都无条件执行的语句
} ]
注意:catch中的异常类型如有子父类关系,子类在上,父类在下,否则报错
//举例
public class IndexOutExp {
public static void main(String[] args) {
String friends[] = { "lisa", "bily", "kessy" };
try {
for (int i = 0; i < 5; i++) {//数组下标越界
System.out.println(friends[i]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("index error");
}
System.out.println("this is the end");
}
}
其二:
声明抛出异常
public void readFile(String file) throws FileNotFoundException { ……
//读文件的操作可能产生FileNotFoundException类型的异常
在此对其进行自动抛出
FileInputStream fis = new FileInputStream(file); ……… }
//举例
import java.io.*;
public class ThrowsTest {
public static void main(String[] args) {
ThrowsTest t = new ThrowsTest();
try {
t.readFile();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFile() throws IOException {
FileInputStream in = new FileInputStream("xieruwenjian.txt");
int b;
b = in.read();
while (b != -1) {
System.out.print((char) b);
b = in.read();
}
in.close();
}
}
而除了已有的异常类以外有时我们还需自己定义一个异常类
定义异常类的要求:
1.继承现有的结构:RuntimeException、Exception
2.提供全局常量SerialVersionUID
3.提供重载的构造器
class MyException extends Exception {
static final long serialVersionUID = 13465653435L;
private int idnumber;
public MyException(String message, int id) {
super(message);
this.idnumber = id;
}
public int getId() {
return idnumber;
}
}
public class MyExpTest {
public void regist(int num) throws MyException {
if (num < 0)
throw new MyException("人数为负值,不合理", 3);
else
System.out.println("登记人数" + num);
}
public void manager() {
try {
regist(100);
} catch (MyException e) {
System.out.print("登记失败,出错种类" + e.getId());
}
System.out.print("本次登记操作结束");
}
public static void main(String args[]) {
MyExpTest t = new MyExpTest();
t.manager();
}
}
而这生成异常类对象,然后通过throw语句实现抛出操作的行为则被称为手动抛出。



