zoukankan      html  css  js  c++  java
  • 第11章 Java异常与异常处理

     

    1.Java异常简介

    1.什么是异常
    异常出现的时候代码会无法正常运行下去,会产生各种问题
    2.捕捉异常的作用
    提早发现异常,方便查找问题,并给出解决方法
    3.Java中的异常
    1.Java中所有不正常的类都是继承与Throeable类,Throwable主要包括两个大类,一个是Error类,一个是Exception类
    Error类主要包括虚拟机错误和线程死锁,一旦Error出现了,程序就彻底挂了,被称为程序终结者;
    Exception类主要指编码、环境、用户操作输入出现问题,Exception主要包括两大类,运行时异常,也是非检查异常(RuntimeException)和检查异常(其他的一些异常)
    RuntimeException异常主要包括以下四种异常:空指针异常,数组下标越界异常,类型转换异常,算术异常。
    分析这四种异常
    空指针异常:NullPointerException

    String str = null;
    System.out.println(str.length());

    数组下标越界异常:ArrayIndexOutOfBoundsException

    int[] ary = {1,2,3}
    for (int i=0; i<=3; i++){
        System.out.println(ary[i]);
    }

    类型转换异常:ClassCastException

    class Animal{
    
    }
    calss Dog extends Animal{
    
    }
    calss Cat extends Animal{
    
    }
    public class Test{
        public static void main(String[] args){
            Animal a1 = new Dog();
            Animal a2 = new Cat();
            Dog d1 = (Dog) a1;
            Dog d2 = (Dog) a2;
        }
    }

    算术异常:ArithmeticException

    int one=12;
    int two=0;
    System.out.println(one/two);

    2.Java中使用rty……catch……finally实现异常处理

    try-catch-finally的使用方法:

    try{
        //一些可能会抛出异常的方法
    }catch(异常类型){
        //处理该异常的代码快11
    }catch(异常类型){
        //处理该异常的代码快22
    }catch(异常类型){
        //处理该异常的代码快33
    }finally{
        //最终将要执行的一些代码
    }

    如果try中的代码发生异常,将发生以下行为:
    1.程序终止执行
    2.程序的控制权将被移交给catch块中的异常处理程序

    关于catch块:
    1.catch中具体执行什么操作根据需要写
    2.可以有多个catch块,try抛出来的异常符合哪一个catch异常类型,就执行哪一个
    3.多个catch块时,先定义小的,具体的,子类的,再定义大的,父类的。catch也遵守就近原则

    关于finall:
    1.是最终要执行的一些代码,即善后处理

    3.案例

    1.try-catch

     1 public class TryCatchTest {
     2     /**
     3      * divide(除数)
     4      * result(结果)
     5      * 每次循环,divide减一,result=result+100/divider
     6      * 如果:捕获异常,打印输出“抛出异常了!!!”,返回-1
     7      * 否则:返回result
     8      */
     9     public int test(){
    10         int divider=10;
    11         int result = 100;
    12         try{
    13             while(divider>-1){
    14                 divider--;
    15                 result=result+100/divider;
    16             }
    17             return result;
    18         }catch (Exception e){
    19             e.printStackTrace();//打印出异常
    20             System.out.println("循环抛出异常了");
    21             return -1;
    22         }
    23 
    24     }
    25 
    26 
    27     public static void main(String[] args) {
    28         TryCatchTest tct = new TryCatchTest();
    29         int result = tct.test();
    30         System.out.println("test()方法,执行完毕,返回的值是:"+result);
    31     }
    32 }

    2.try-catch-finally

     1 public class TryCatchTest {
     2     /**
     3      * divide(除数)
     4      * result(结果)
     5      * 每次循环,divide减一,result=result+100/divider
     6      * 如果:捕获异常,打印输出“抛出异常了!!!”,返回999
     7      * 否则:返回result
     8      * fianlly:打印“这是finally输出!!”
     9      */
    10     public int test2(){
    11         int divider=10;
    12         int result = 100;
    13         try{
    14             while(divider>-1){
    15                 divider--;
    16                 result=result+100/divider;
    17             }
    18             return result;
    19         }catch (Exception e){
    20             e.printStackTrace();//打印出异常
    21             System.out.println("循环抛出异常了"); //此处的catch被捕获,并打印
    22             return result=999; //返回result
    23         }finally {
    24             System.out.println("这是finally!!");//执行了finally
    25             System.out.println("我是Result,我的值是:"+result);
    26         }
    27 
    28     }
    29 
    30 
    31 
    32     public static void main(String[] args) {
    33         TryCatchTest tct = new TryCatchTest();
    34         int result2 = tct.test2();
    35         System.out.println("我想大声告诉你,test()执行完毕,return="+result2);
    36     }
    37 }
    38 
    39 …………
    40 java.lang.ArithmeticException:(省略)
    41 循环抛出异常了
    42 这是finally!!
    43 我是Result,我的值是:999
    44 我想大声告诉你,test()执行完毕,return=999

    4.Java中的异常抛出

    4.1.throw和throws的使用

    java中的异常处理有三种方式,第一种是系统自动抛出,就是我们上面讲的那些,第二种是针对语句使用的throw,第三种是针对方法使用的throws
    第一种已经讲过了,看看第二种,throw的用法
    throw是语句抛出一个异常
    语法:

    语法:throw (异常对象);
    如:throw e;

    一般用与程序出现某种逻辑时,程序员主动的抛出某种特定类型的异常

    public static void main(String[] args) {  
            String s = "abc";  
            if(s.equals("abc")) {  
                throw new NumberFormatException();  
            } else {  
                System.out.println(s);  
            }  
            //function();  
    }

    会抛出异常:NumberFormatException()
    throws
    throws是方法可能抛出的异常(用在申明方法时,表示该方法可能要抛出异常)
    语法:

    [修饰符] 返回值 方法名([参数列表]) [throws(异常类)]{
    …………
    }

    当每个方法可能会抛出某种异常时用于throws声明可能抛出的异常,虽然异常抛出了,但是处理这个异常是在调用这个方法的时候处理

    //throws抛出function()可能会产生的一个异常
        public static void function() throws NumberFormatException{  
                String s = "abc";  
                System.out.println(Double.parseDouble(s));  
            }  
    
    
    
            public static void main(String[] args) {  
            //调用了function()方法,则要处理这个方法抛出来的异常
                try {  
                    function();  
                } catch (NumberFormatException e) {  
                    System.err.println("非数据类型不能转换。");  
                    //e.printStackTrace();  
                }  
        }

    4.2.throw和throws的比较

    1.throws出现在方法函数头,而throw出现在函数体
    2.throws表示出现异常的一种可能性,并不一定要发生这些异常,throw则是抛出了异常,执行throw则一定抛出某种异常
    3.两者都是抛出异常,自己并不出理,都是由调用的它的地方来处理

    5.Java中的异常总结

    1.处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
    2.在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
    3.对于不确定的代码,也可以加上try-catch,处理潜在的异常
    4.尽量去处理异常,切忌只是简单的调用printStackTrace()去打印输出
    5.具体如何处理异常,要根据不同的业务需求和异常类型去决定
    6.尽量添加finally语句块去释放占用的资源

  • 相关阅读:
    理解Python中的__init__和__new__
    Python内置数学函数
    Java实现邮箱验证
    Socket通信
    Jvm内存模型
    Java GC如何判断对象是否为垃圾
    ::符号
    替换特殊符号
    有意思的小知识
    有意思的小题目
  • 原文地址:https://www.cnblogs.com/cenyu/p/6093283.html
Copyright © 2011-2022 走看看