Think in Java 筆記_Chapter12_1_Exception基礎_異常處理2

來源:互聯網
上載者:User

標籤:

異常處理方式2

  1. throw向上拋出
    package cn.seven.shengsiyuan.exception;/* * 2015年04月05日13:05:35 * Location:501 *  * 異常處理方法2:拋出異常,由調用該方法的方法  進行處理該異常 */public class ExceptionThrowDemo {public static void main(String[] args) throws Exception {// TODO Auto-generated method stubExceptionThrowDemo demo = new ExceptionThrowDemo();//demo.method();//若直接這樣寫 出現 Unhandled exception type Exceptiondemo.method();//因此需對該異常進行處理:兩種方式,1.自己處理 2.向上拋出:main方法中拋出到最後就是虛擬機器進行處理了}public void method () throws Exception{//告訴調用該方法這個其他方法,我這個方法會拋出異常System.out.println("hello");throw new Exception();//拋出一個異常對象,因為所有的一場都是異常}}

     

  2. 有些異常 編譯時間候 可以通過,有些異常不可以通過,為何?
      1. int a = 3;int b = 0;int c= a / b;//這裡即使可能拋出異常,但是編譯通過,運行時拋出異常`    System.out.println("---hello---");

      2. /* 拋出的異常,編譯不通過,因為異常的類型:--CheckedException(非運行時異常),在編譯時間候就需要進行處理_處理方式兩種:1,try{}catch{}2, 在調用該會產生異常的方法 所在的方法聲明 throws Exception--對於UncheckedException(運行時異常),如c=a/b;我們可以對其進行處理,也可以不處理,推薦不處理*/public static void main(String[] args) {ExceptionThrowDemo demo = new ExceptionThrowDemo();demo.method();//若直接這樣寫 出現 Unhandled exception type Exception}public void method () throws Exception{//告訴調用該方法這個其他方法,我這個方法會拋出異常System.out.println("method");throw new Exception();//拋出一個異常對象,因為所有的一場都是異常}

Think in Java 筆記_Chapter12_1_Exception基礎_異常處理2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.