Java把异常当做对象处理,并定义一个基类java.lang.Throwable作为所有异常的超类
在Java API 中已经定义了许多异常类,这些异常类分为两类,错误Error和异常Exception。
Error
Exception
在Exception分支中有一个重要的子类RuntimeException(运行时异常)
ArryIndexOutOfBoundsException(数组下标越界)
NullPointerException(空指针异常)
ArithmeticException(算术异常)
MissingResourceException(丢失资源)
ClasssNotFoundException(找不到类)
等异常,这些异常是不检查异常,程序中可以选择捕获异常,也可以不处理
这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这里异常发送
Error和Exception的区别:Error通常是灾难性的致命的错误,是程序无法控制和处理的,当出现这些异常时,Java虚拟机一般会选择终止线程;Exception通常情况下是可以被程序处理的,并且在程序中应该尽可能的去处理这些异常。
package com.exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设捕获多个异常,从小到大!
try {//try监控区域
if(b==0){
throw new ArithmeticException("数据不能等于0");
}else{
System.out.println(a/b);
}
} catch (Error e) {//catch捕获异常(捕获异常类型)
System.out.println("有个问题");
}catch(Throwable e){
e.printStackTrace();//打印系统错误信息
} finally{//处理善后工资
System.out.println("继续输出");
}
try {
new Test().test(a, b);
} catch (ArithmeticException e) {
e.printStackTrace();
}finally{//处理善后工资
System.out.println("继续输出");
}
//finally可以不写,假设IO,资源的关闭!
}
//方法抛出异常用throws
public void test(int a,int b) throws ArithmeticException {
System.out.println(a/b);
}
}
package com.exception;
//自定义异常类,继承exception类
public class MyException extends Exception {
//传统数字>10
private int detail;
public MyException( int detail) {
this.detail = detail;
}
@Override
public String toString() {
return "MyException [detail=" + detail + "]";
}
}
package com.exception;
public class Test {
public static void main(String[] args) {
try {
test(11);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void test(int a) throws MyException {
if(a>10){
throw new MyException(a);
}
}
}
原文:https://www.cnblogs.com/novice77/p/14602290.html