1、什么是异常(Throwable)?
Throwable 类是 Java 语言中所有错误或异常的超类。只有当对象是此类(或其子类之一)的实例时,才能通过 Java 虚拟机或者 Java throw 语句抛出。类似地,只有此类或其子类之一才可以是 catch 子句中的参数类型。
2、其子类
1)Error:称为错误类,表示Java运行时产生的系统内部错误或资源耗尽的错误,是比较严重的,仅靠修改程序本身是不能够恢复执行的
2)Exception:称为异常类,表示程序本身可以处理的错误
3、Throwable类的常用方法
1)getMessage()
: 返回此 throwable 的详细消息字符串。
2)getStackTrace()
:提供编程访问由 printStackTrace()
输出的堆栈跟踪信息。
3)printStackTrace(PrintStream s)
:将此 throwable 及其追踪输出到指定的输出流。
4、常见异常及其处理方式
1)try....catch
2)finally:无论如何都要运行的代码块,除非前面虚拟机关闭
and so on;
接下来用代码实现其功能:
ackage Exception_original;
/*Exception:1)Exception指还可以通过修改程序恢复运行的异常
* 2)是Throwable的子类之一
* 3)其子类数目繁多,具体遇见再分析
* 异常的处理分为两种:
* 1)try...catch...finally (标准格式) :捕获异常
* 2)throws ... 抛出异常
*
* */
public class Exception_original_trycathch1 {
private static final int b = 0;
private static final int x = 0;
public static void main(String[] args) {
// int a = 10;
// int b = 0;
// System.out.println(a/b);//java.lang.ArithmeticException: / by
// zero出现算数异常,被除数不能为0;若要使程序运行下去:
// 只有一个异常需要被处理时
// 加入try...catch
// try{
// int a = 10;
// int b = 0;
// int number = a/b;
// }catch(Exception e){
// System.out.println("捕获的异常信息:"+e.getMessage());//捕获的异常信息:/ by zero
// System.out.println(e.toString());//java.lang.ArithmeticException: /
// by zero
// }
// 有两个或两个以上的异常时:
int x = 2;
int y = 0;
// int[]arr = {0,1};
try {
System.out.println(x / y);
// System.out.println(arr[2]); //ArrayIndexOutOfBoundsException
} catch (ArithmeticException a) {
System.out.println("捕获的异常信息:" + a.getMessage());// 捕获的异常信息:/ by zero
}
int[] arr = { 0, 1 };
try {
System.out.println(arr[2]); // ArrayIndexOutOfBoundsException:用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引
} catch (ArrayIndexOutOfBoundsException ar) {
System.out.println("捕获的异常信息:" + ar.getMessage());// 捕获的异常信息:2
return; //结束当前语句(对finally代码块无效);只有关闭虚拟机才能阻挡finally代码块的运行;
}
// System.out.println("程序继续执行");// 程序继续执行
finally{
System.out.println("进入finally代码块"); //进入finally代码块
}
}
}
package Exception_original;
/*jdk7以后出现另一种方式处理多个异常
*
* try{
* 可能出现问题的代码;
* }catch(异常类名1 | 异常类名2 |... 对象名){
*
* 处理异常
* }
*
* */
public class Exception_original_trycathch2 {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int number = a / b;
int[] x = { 0, 1 };
int y = x[2];
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("出错了"); // 出错了
}
}
}