异常处理
异常在JAVA中代表一个错误的实体对象.
JAVA中用try catch finally关键字来捕捉错误
public class CheckArgsDemo {
public static void main(String[] args) {
try {
System.out.printf("执行 %s 功能%n", args[0]);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("没有指定变量");
e.printStackTrace();
}
}
}
可控式异常(Checked Exception),这种错误可以预计发生的.
import java.io.*;
public class CheckedExceptionDemo {
public static void main(String[] args) {
try {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入整数: ");
int input = Integer.parseInt(buf.readLine());
System.out.println("input x 10 = " + (input*10));
}
catch(IOException e) {
System.out.println("I/O错误");
}
catch(NumberFormatException e) {
System.out.println("输入必须为整数");
}
}
catch(IOException e) {
System.out.println("I/O错误");
}
/*这个是一个可控式的错误,是可以预期会发生的异常.编译器要求你处理.
如果没有catch(IOException e)的话
编译出错:CheckedExceptionDemo.java:8: 未报告的异常 java.io.IOException;必须对其进行捕捉或声明以便抛出
int input = Integer.parseInt(buf.readLine());
^
1 错误*/
finally关键字,如果程序出现这个关键字的话,程序就会在最后处理这个异常.
throw 和 throws
/*
如果想要自行丢出异常就用THROW,并生成指定的异常对象.
*/
public class ThrowDemo {
public static void main(String[] args) {
try {
double data = 100 / 0.0;
System.out.println("浮点数除以零:" + data);
if(String.valueOf(data).equals("Infinity"))
throw new ArithmeticException("除零异常");//程序自行建立一个 ArithmeticException实例丢出
}
catch(ArithmeticException e) {
System.out.println(e);
}
}
}
运行运行结果:
浮点数除以零:Infinity
java.lang.ArithmeticException: 除零异常
/*
如果在方法中发省了异常,而并不想在方法中直接处理,而想要由调用方法的调用者来处理
则可以使用throws关键字来声明这个方法将会丢出异常
*/
public class ThrowsDemo {
public static void main(String[] args) {
try {
throwsTest();
}
catch(ArithmeticException e) {
System.out.println("捕捉异常");
}
}
private static void throwsTest() throws ArithmeticException {
System.out.println("这只是一个测试");
// 程序处理过程假设发生异常
throw new ArithmeticException();
}
}
/*
简单来讲:要么在方法中直接处理异常
要么就在方法上声明该方法会丢回异常,由调用它的调用者来处理
*/
运行运行结果:
这只是一个测试
捕捉异常
try … catch的捕捉顺序
通过以下两个顺序来写明
import java.io.*;
public class ExceptionDemo {
public static void main(String[] args) {
try {
throw new ArithmeticException("异常测试");
}
catch(Exception e) {
System.out.println(e.toString());
}
catch(ArithmeticException e) {
System.out.println(e.toString());
}
}
}
程序说明
//Exception是ArithmeticException的父类,所以new ArithmeticException("异常测试"); 实例先被Exception的catch捕捉到, 出现编译错误
ExceptionDemo.java:11: 已捕捉到异常 java.lang.ArithmeticException
catch(ArithmeticException e) {
^
1 错误
import java.io.*;
public class ExceptionDemo2 {
public static void main(String[] args) {
try {
throw new ArithmeticException("异常测试");
}
catch(ArithmeticException e) {
System.out.println(e.toString());
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
运行结果:
java.lang.ArithmeticException: 异常测试
在这个程序里面