Java中手動(dòng)拋異常和捕獲異常

import java.io.IOException;

public class Test3 {

public static void main(String[] args) {

// TODO Auto-generated method stub

//

// method3();

// method4();

// try {

method5(10,1);

// } catch (IOException e) {

// TODO Auto-generated catch block

// e.printStackTrace();

// }

}

// 手動(dòng)拋異常使用throw

// throws 與 throw 區(qū)別

public static int method5(int a,int b)? {

if(b==0) {

throw new RuntimeException();

}else if(b==1) {

// throw new IOException();

}

return a/b;

}

public static void method4() {

System.out.println("open");

try {

System.out.println(10/0);

// return ;

// System.exit(0);

}catch(Exception e){

System.out.println(e);

}finally {

System.out.println("close");

}

}

// 捕獲不同種類的異常時(shí) 有兩種解決方案

// 1.寫多個(gè)catch?

// 2.寫Exception 可以捕獲其他所有異常

// 3.在jdk1.7以后 單個(gè)catch可以捕獲多個(gè)異常 (不能出現(xiàn)父子關(guān)系)

// 寫多個(gè)catch時(shí)注意 子類寫在前,父類寫在后

public static void method3() {

//

Person p=new Person();

p=null;

try {

// p.say();

System.out.println(10/0);

}

catch(ArithmeticException|NullPointerException e) {? //ArithmeticException

System.err.println("捕獲到了異常"+e);

}catch(Exception e) {

System.err.println("父類可以捕獲子類異常");

}

//NullPointerException

}

public static void method1() {

// Person p=new Person();

Person p=null;

p.say();

}

public static void method2() {

method1();

}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容