JavaSE-08 Exception异常机制
1.异常例子:com.fenfen.exception.Demo1
- StackOverflowError
public class Demo1 {
public static void main(String[] args) {
new Demo1().a();
//会出现StackOverflowError
}
public void a(){
b();
}
public void b() {
a();
}
}
- ArithmeticException
public class Demo01 {
public static void main(String[] args) {
System.out.println(11/0);//异常类型:ArithmeticException
}
}
2.异常体系结构
分为Error和Exception:
2.1 Error:
- 虚拟机异常
- gui编程异常
2.2 Exception:
-
IO异常:
-
运行时异常:
-
找不到类异常ClassNotFoundException
-
空指针异常NullPointException
-
数组下标越界ArrayIndexOutOfBoundsException
-
未知的类型异常UnkownTypeException
-
算术异常ArithmeticException
3.异常处理机制
- try,catch,finally
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
//try 监控区域
System.out.println(a/b);
}catch(ArithmeticException e){//捕获异常:如果try异常就走catch中间的
System.out.println("程序出现异常,变量b不能为0");
}finally {//处理善后工作
System.out.println("finally");
}
/*
finally可以不要,finally一般用在io流的关闭
*/
}
}
- 多个异常捕获catch
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
//try 监控区域
new Test1().a();
}catch(Error e) {//想要捕获的异常类型,可以写多个:从小到大
System.out.println("Error");
}catch(Exception e) {
System.out.println("Exception");
}catch(Throwable e) {
System.out.println("Throwable");
} finally {//处理善后工作
System.out.println("finally");
}
}
//写两个方法互相调用
public void a(){
b();
}
public void b(){
a();
}
}
- 主动抛出异常throw
public static void main(String[] args) {
try {
new Test0().test(1,0);
} catch (ArithmeticException e) {//接收下面排除的异常,捕获一下,保证程序可以正常与运行
e.printStackTrace();
}
}
//假设这方法中,处理不了这个异常,方法上抛出异常
public void test(int a, int b) throws ArithmeticException{
if (b == 0) {//throw
throw new ArithmeticException();
}
System.out.println(a / b);
}
}
4. 自定义异常:com.fenfen.exception.Demo2
- 自定义MyException类
public class MyException extends Exception{
//传递数字
private int detail;
//整一个构造器:消息构造器
public MyException(int a) {
this.detail = a;
}
//toString:异常的打印信息
@Override
public String toString() {
//增加一些处理异常的代码块
return "MyException{" + detail + '}';
}
}
- 使用自定义异常
public class Test {
//可能会存在异常的方法
static void test(int a) throws MyException {
System.out.println("传递的参数为:"+a);
if(a>10){
//throw new MyException(a);到这边有两种选择,一个捕获,一个抛出去
throw new MyException(a);//这边选择抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
//记得用try,catch捕获一下
try {
test(11);
} catch (MyException e) {//接收抛出的异常
System.out.println("MyException=>"+e);
}
}