1. 程式人生 > 其它 >Java異常01——捕獲和丟擲異常

Java異常01——捕獲和丟擲異常

捕獲和丟擲異常

異常處理五個關鍵字

try , catch , finally , throw , throws

try catch finally(快捷鍵:選中要要監控的程式碼語句 快捷鍵: ctrl + alt + t)
package exception;

public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;

try{//try 監控區域
System.out.println(a/b);
}catch (ArithmeticException e){//catch 捕獲異常
System.out.println("程式出現異常,b不能為0");
}finally {// 處理善後工作
System.out.println("finally");
}

//finally 可以不要finally, 用: 假設IO,資源需要關閉

}
}
---------------------------------------------------------------------------------------------------

// 選中要要監控的程式碼語句 快捷鍵: ctrl + alt + t
package exception;

public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;

// 假設要捕獲多個異常: 異常型別:從小到大

try{//try 監控區域
System.out.println(a/b);
}catch (Error e){//catch(想要捕獲的異常型別!) 捕獲異常
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
}
finally {// 處理善後工作
System.out.println("finally");
}

//finally 可以不要finally, 用: 假設IO,資源需要關閉

}
}
throw throws
package exception;

public class Test {
public static void main(String[] args) {

new Test().test(1,0);
}

public void test(int a , int b){
if(b==0){// throw throws
throw new ArithmeticException();//主動丟擲異常,一般在方法中使用 throw
}
System.out.println(a/b);
}
}
---------------------
package exception;

public class Test {
public static void main(String[] args) {

try {
new Test().test(1,0); // try catch
} catch (ArithmeticException e) {
e.printStackTrace();
}
}

// 假設這個方法中,處理不了這個異常。方法上丟擲異常
public void test(int a , int b) throws ArithmeticException{ // throws
if(b==0){// throw throws
throw new ArithmeticException();//主動丟擲異常,一般在方法中使用
}
System.out.println(a/b);
}
}

學習內容源自視訊:b站狂神說Java