Java异常处理详解

异常处理详解

1、异常的定义

​   ①异常(Exception)—程序运行中出现的不期而至的各种状况,如文件找不到、网络连接失败、非法参数等

​   ②异常的分类

​     1.检查性异常:用户错误或问题引起的异常,是程序员无法预见的,如打开一个不存在文件时

​     2.运行时异常:能被程序员避免的异常

​     3.错误(ERROR):错误不是异常,而是脱离程序员控制的问题,如栈溢出时

 

2、异常体系结构

​   ①Java把异常当作对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类。异常分为两大类:错误(Error)和异常(Exception)

                

​   ②Error和Exception区别

​     Error—由Java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关;Error通常是灾难性致命错误

​     Exception—一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这类异常的发生;通常情况下是可以被程序处理的

 

3、异常处理机制

​   ①通过try—catch—finally语句对异常进行处理

 1 public class Test {
 2     public static void main(String[] args) {
 3         int a=1;
 4         int b=0;
 5 
 6         //Ctrl+Alt+T 选中语句加快捷键,可以快速写出该结构
 7         try {   //try监控区域
 8             System.out.println(a/b);
 9         }catch(Error error){    //catch(想要捕获的异常类型)  捕获异常
10             System.out.println("Error");
11         } catch (Exception e) {
12             System.out.println("Exception");
13         }catch(Throwable throwable){
14             System.out.println("Throwable");
15         }finally {     //处理善后工作;可选;一定会执行
16             System.out.println("finally");
17         }
18         
19         //catch语句可以有多条,但捕获的异常类型一定要从小范围到大范围
20     }
21 }

​    ②主动抛出异常

 1 public class Demo1 {
 2     public static void main(String[] args) {
 3         new Demo1().test(3,0);
 4     }
 5 
 6     public void test(int a,int b){
 7         if(b==0){
 8             throw new ArithmeticException();    //主动抛出异常,一般在方法中使用
 9         }
10     }
11 }

  ③方法中无法处理异常,就将该方法抛给调用它的对象处理

 1 public class Demo1 {
 2     public static void main(String[] args) {
 3         try {
 4             new Demo1().test(3,0);
 5         } catch (ArithmeticException e) {
 6             System.out.println("ArithmeticException");
 7         }
 8     }
 9 
10     //假设这方法中,处理不了这个异常,方法上抛出异常
11     public void test(int a,int b) throws ArithmeticException{
12         if(b==0){
13             throw new ArithmeticException();    //主动抛出异常,一般在方法中使用
14         }
15     }
16 }

 

4、自定义异常

​    用户自定义异常类,只需继承Exception类

 1 //自定义异常类
 2 public class MyException extends Exception{
 3     private int datail;
 4 
 5     public MyException(int datail) {
 6         this.datail = datail;
 7     }
 8 
 9     @Override
10     public String toString() {
11         return "MyException{" + datail + '}';
12     }
13 }
14 
15 //应用类
16 public class Application {
17     public static void main(String[] args) {
18         try {
19             test(16);
20         } catch (MyException e) {
21             System.out.println(e);
22         }
23     }
24     static void test(int a) throws MyException {
25         if(a>10){
26             throw new MyException(a);       //主动抛出异常
27         }else{
28             System.out.println("OK");
29         }
30     }
31 }

 

posted @ 2021-02-10 13:53  sumAll  阅读(129)  评论(0)    收藏  举报