3.Java異常進階

來源:互聯網
上載者:User

標籤:on()   string   傳回值   code   相對   ring   rgs   ide   get   

3.JAVA異常進階1.Run函數中拋出的異常

  • 1.run函數不會拋出異常
  • 2.run函數的異常會交給UncaughtExceptionhandler處理
  • 3.預設的UncaughtExceptionHandler為空白   Thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){…...})
  • 4.啟動線程 Thread.start()
  • 例子
  •  UncaughtExceptionTask task=new UncaughtExceptionTask();        Thread thread = new Thread(task);        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {            @Override            public void uncaughtException(Thread t, Throwable e) {                System.out.println("處理run函數拋出的異常");                System.out.println(t+":"+e);            }        });        thread.start();    } class UncaughtExceptionTask implements Runnable{    public void run(){        System.out.println(10/0);//throws uncheckerException: ArithmeticException    }} 

 

 

  • 對異常進行捕獲
  • public class ExceptionTest {    public static void main(String[] args) {        int c=0;        try {            int a = 3;            int b = 0;            c=a/b;            System.out.println(c);        }  catch (Exception e) {            e.printStackTrace();        } finally {            System.out.println("處理了異常: ArithmeticException");        }        System.out.println(c);    }}
  • 拋出異常,但是程式可以繼續向下執行,此時輸出的c為沒有進入try塊的初始化的值---注意c的值是0;
  • 若c=10/2,運行結束不會拋出異常,c為5;

 

  • 函式宣告時候指定拋出的異常名
  • void function() throws MyException{/*code*/}
  • a.函數code拋出的異常類型必須與函數throws的異常類型對應
  • b.函數code可以不拋出異常(如果拋出異常就必須與throws的異常類型相對應)

 

  • 異常資訊顯示
  • Exception.printstackTrace();
  • Exception.printstackTrace(System.out);—輸出重新導向
  • Exception.getMessage();
  • Exception.getstackTrace();—傳回值是一個數組
  • 最主要的異常資訊提取函數還是e.printStackTrace();
  • printStackTrace();
  • 函數功能:列印出異常拋出的處和函數的調用路徑
  • 預設的輸出路徑 System.err 標準錯誤流
  • 重新導向輸出printStackTrace(System.out);

 

3.Java異常進階

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.