package com.exception.demo01;
public class demo01 {
public static void main(String[] args) {
try{new demo01().a();}//StackOverflowError例外
catch (Throwable e){
System.out.println("程式出現例外");
}
//System.out.println(11/0);//ArithmeticException例外
}
public void a(){
b();
}
public void b(){
a();
}
}
package com.exception.demo01;
public class Test {
public static void main(String[] args) {
int a=1;
int b=0;
//假設要捕獲多個例外,從小到大
try {
new Test().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void a(){
b();
}
public void b(){
a();
}
//假設這個給方法中處理不了這個給例外,方法上拋出例外 throws
public void test(int a,int b) throws ArithmeticException {
if(b==0){
throw new ArithmeticException();//主動拋出例外 throw 一般在方法中使用
}
System.out.println(a/b);
}
}
/*
假設要捕獲多個例外,從小到大
try {//try是監控區域
new Test().a();
} catch (Error e){//catch(想要捕獲的例外型別)捕獲例外
System.out.println("程式1出現例外被除數不能為0");}
/*catch (ArithmeticException e){//catch(想要捕獲的例外型別)捕獲例外
System.out.println("程式出現例外被除數不能為0");}
catch (Exception e){
System.out.println("程式2出現例外被除數不能為0");
}
catch (Throwable t){
System.out.println("程式3出現例外被除數不能為0");
}
finally {//處理善后作業
System.out.println("finally");
}
//finally可以不要 finally,假設IO,資源,關閉
*/
package com.exception.demo01;
public class Test2 {
public static void main(String[] args) {
int a=1;
int b=0;
//Ctrl+Alt+T 生成try carch的快捷鍵
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();//列印錯誤的堆疊資訊
} finally {
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/473413.html
標籤:Java
上一篇:二刷SSM-Day1
下一篇:java中如何生成UUID呢?
