1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        Java 異常處理的十個(gè)建議

        共 6521字,需瀏覽 14分鐘

         ·

        2021-01-05 09:39

        前言

        Java異常處理的十個(gè)建議,希望對(duì)大家有幫助~

        一、盡量不要使用e.printStackTrace(),而是使用log打印。

        反例:

        try{  // do what you want  }catch(Exception e){  e.printStackTrace();}

        正例:

        try{  // do what you want  }catch(Exception e){  log.info("你的程序有異常啦,{}",e);}

        理由:

        • printStackTrace()打印出的堆棧日志跟業(yè)務(wù)代碼日志是交錯(cuò)混合在一起的,排查異常日志不太方便。
        • e.printStackTrace()語句產(chǎn)生的字符串記錄的是堆棧信息,如果信息太長太多,字符串常量池所在的內(nèi)存塊沒有空間了,即內(nèi)存滿了,那么,用戶的請(qǐng)求就卡住啦~

        二、catch了異常,但是沒有打印出具體的exception,無法更好定位問題

        反例:

        try{  // do what you want  }catch(Exception e){  log.info("你的程序有異常啦");}

        正例:

        try{  // do what you want  }catch(Exception e){  log.info("你的程序有異常啦,{}",e);}

        理由:

        • 反例中,并沒有把exception出來,到時(shí)候排查問題就不好查了啦,到底是SQl寫錯(cuò)的異常還是IO異常,還是其他呢?所以應(yīng)該把exception打印到日志中哦~

        三、不要用一個(gè)Exception捕捉所有可能的異常

        反例:

        public void test(){    try{        //…拋出 IOException 的代碼調(diào)用        //…拋出 SQLException 的代碼調(diào)用    }catch(Exception e){        //用基類 Exception 捕捉的所有可能的異常,如果多個(gè)層次都這樣捕捉,會(huì)丟失原始異常的有效信息哦        log.info(“Exception in test,exception:{}”, e);    }}

        正例:

        public void test(){    try{        //…拋出 IOException 的代碼調(diào)用        //…拋出 SQLException 的代碼調(diào)用    }catch(IOException e){        //僅僅捕捉 IOException        log.info(“IOException in test,exception:{}”, e);    }catch(SQLException e){        //僅僅捕捉 SQLException        log.info(“SQLException in test,exception:{}”, e);    }}

        理由:

        • 用基類 Exception 捕捉的所有可能的異常,如果多個(gè)層次都這樣捕捉,會(huì)丟失原始異常的有效信息哦

        四、記得使用finally關(guān)閉流資源或者直接使用try-with-resource

        反例:

        FileInputStream fdIn = null;try {    fdIn = new FileInputStream(new File("/jay.txt"));    //在這里關(guān)閉流資源?有沒有問題呢?如果發(fā)生異常了呢?    fdIn.close();} catch (FileNotFoundException e) {    log.error(e);} catch (IOException e) {    log.error(e);}

        正例1:

        需要使用finally關(guān)閉流資源,如下

        FileInputStream fdIn = null;try {    fdIn = new FileInputStream(new File("/jay.txt"));} catch (FileNotFoundException e) {    log.error(e);} catch (IOException e) {    log.error(e);}finally {    try {        if (fdIn != null) {            fdIn.close();        }    } catch (IOException e) {        log.error(e);    }}

        正例2:

        當(dāng)然,也可以使用JDK7的新特性try-with-resource來處理,它是Java7提供的一個(gè)新功能,它用于自動(dòng)資源管理。

        • 資源是指在程序用完了之后必須要關(guān)閉的對(duì)象。
        • try-with-resources保證了每個(gè)聲明了的資源在語句結(jié)束的時(shí)候會(huì)被關(guān)閉
        • 什么樣的對(duì)象才能當(dāng)做資源使用呢?只要實(shí)現(xiàn)了java.lang.AutoCloseable接口或者java.io.Closeable接口的對(duì)象,都OK。
        try (FileInputStream inputStream = new FileInputStream(new File("jay.txt")) {    // use resources   } catch (FileNotFoundException e) {    log.error(e);} catch (IOException e) {    log.error(e);}

        理由:

        • 如果不使用finally或者try-with-resource,當(dāng)程序發(fā)生異常,IO資源流沒關(guān)閉,那么這個(gè)IO資源就會(huì)被他一直占著,這樣別人就沒有辦法用了,這就造成資源浪費(fèi)。

        五、捕獲異常與拋出異常必須是完全匹配,或者捕獲異常是拋異常的父類

        反例:

        //BizException 是 Exception 的子類public class BizException extends Exception {}//拋出父類Exceptionpublic static void test() throws Exception {}
        try { test(); //編譯錯(cuò)誤} catch (BizException e) { //捕獲異常子類是沒法匹配的哦 log.error(e);}

        正例:

        //拋出子類Exceptionpublic static void test() throws BizException {}
        try { test();} catch (Exception e) { log.error(e);}

        六、捕獲到的異常,不能忽略它,至少打點(diǎn)日志吧

        反例:

        public static void testIgnoreException() throws Exception {    try {               // 搞事情    } catch (Exception e) {     //一般不會(huì)有這個(gè)異常            }}

        正例:

        public static void testIgnoreException() {    try {        // 搞事情    } catch (Exception e) {     //一般不會(huì)有這個(gè)異常        log.error("這個(gè)異常不應(yīng)該在這里出現(xiàn)的,{}",e);     }}

        理由:

        • 雖然一個(gè)正常情況都不會(huì)發(fā)生的異常,但是如果你捕獲到它,就不要忽略呀,至少打個(gè)日志吧~

        七、注意異常對(duì)你的代碼層次結(jié)構(gòu)的侵染(早發(fā)現(xiàn)早處理)

        反例:

        public UserInfo queryUserInfoByUserId(Long userid) throw SQLException {    //根據(jù)用戶Id查詢數(shù)據(jù)庫}

        正例:

        public UserInfo queryUserInfoByUserId(Long userid) {    try{        //根據(jù)用戶Id查詢數(shù)據(jù)庫    }catch(SQLException e){        log.error("查詢數(shù)據(jù)庫異常啦,{}",e);    }finally{        //關(guān)閉連接,清理資源    }}

        理由:

        • 我們的項(xiàng)目,一般都會(huì)把代碼分 Action、Service、Dao 等不同的層次結(jié)構(gòu),如果你是DAO層處理的異常,盡早處理吧,如果往上 throw SQLException,上層代碼就還是要try catch處理啦,這就污染了你的代碼~

        八、自定義封裝異常,不要丟棄原始異常的信息Throwable cause

        我們常常會(huì)想要在捕獲一個(gè)異常后拋出另一個(gè)異常,并且希望把原始異常的信息保存下來,這被稱為異常鏈。公司的框架提供統(tǒng)一異常處理就用到異常鏈,我們自定義封裝異常,不要丟棄原始異常的信息,否則排查問題就頭疼啦

        反例:

        public class TestChainException {    public void readFile() throws MyException{        try {            InputStream is = new FileInputStream("jay.txt");            Scanner in = new Scanner(is);            while (in.hasNext()) {                System.out.println(in.next());            }        } catch (FileNotFoundException e) {            //e 保存異常信息            throw new MyException("文件在哪里呢");        }    }    public void invokeReadFile() throws MyException{        try {            readFile();        } catch (MyException e) {            //e 保存異常信息            throw new MyException("文件找不到");        }    }    public static void main(String[] args) {        TestChainException t = new TestChainException();        try {            t.invokeReadFile();        } catch (MyException e) {            e.printStackTrace();        }    }}//MyException 構(gòu)造器public MyException(String message) {        super(message);    }

        運(yùn)行結(jié)果如下,沒有了Throwable cause,不好排查是什么異常了啦

        正例:


        public class TestChainException { public void readFile() throws MyException{ try { InputStream is = new FileInputStream("jay.txt"); Scanner in = new Scanner(is); while (in.hasNext()) { System.out.println(in.next()); } } catch (FileNotFoundException e) { //e 保存異常信息 throw new MyException("文件在哪里呢", e); } } public void invokeReadFile() throws MyException{ try { readFile(); } catch (MyException e) { //e 保存異常信息 throw new MyException("文件找不到", e); } } public static void main(String[] args) { TestChainException t = new TestChainException(); try { t.invokeReadFile(); } catch (MyException e) { e.printStackTrace(); } }}//MyException 構(gòu)造器public MyException(String message, Throwable cause) { super(message, cause); }

        九、運(yùn)行時(shí)異常RuntimeException ,不應(yīng)該通過catch 的方式來處理,而是先預(yù)檢查,比如:NullPointerException處理

        反例:

        try {  obj.method() } catch (NullPointerException e) {...}

        正例:

        if (obj != null){   ...}

        十、注意異常匹配的順序,優(yōu)先捕獲具體的異常

        注意異常的匹配順序,因?yàn)橹挥械谝粋€(gè)匹配到異常的catch塊才會(huì)被執(zhí)行。如果你希望看到,是NumberFormatException異常,就拋出NumberFormatException,如果是IllegalArgumentException就拋出IllegalArgumentException。

        反例:

        try {    doSomething("test exception");} catch (IllegalArgumentException e) {           log.error(e);} catch (NumberFormatException e) {    log.error(e);}

        正例:

        try {    doSomething("test exception");} catch (NumberFormatException e) {           log.error(e);} catch (IllegalArgumentException e) {    log.error(e);}

        理由:

        • 因?yàn)镹umberFormatException是IllegalArgumentException 的子類,反例中,不管是哪個(gè)異常,都會(huì)匹配到IllegalArgumentException,就不會(huì)再往下執(zhí)行啦,因此不知道是否是NumberFormatException。所以需要優(yōu)先捕獲具體的異常,把NumberFormatException放前面~
        瀏覽 41
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            破外女一级视频免费出血 | 国产午夜免费福利 | 91三级片在线观看 | 久久久AV电影 | 插下面网站| www.狠狠草 | 少妇饥渴偷公乱第28章 | 国产无码性爱 | 天天综合色中文字幕 | 天堂草原电视剧在线观看红桃 |