1.什么是異常:
異常的分類:
package com.sj.exception;
public class Demo01 {
public static void main(String[] args) {
System.out.println(11/0);
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.sj.exception.Demo01.main(Demo01.java:5)
Process finished with exit code 1
2.異常體系結構:
Error:
Exception:
3.Java異常處理機制:
4.處理異常:
package com.sj.exception;
public class Test {
public static void main(String[] args) {
new Test().test(1,0);
//finally 可以不要finally, 假設IO流,資源,關閉
}
//假設這個方法中,處理不了這個異常。方法上拋出異常
public void test(int a,int b) throws ArithmeticException{
if (b==0){// throw throws
throw new ArithmeticException();//主動的拋出異常,一般在方法中使用
}
System.out.println(a/b);
}
}
/*
//假設要捕獲多個異常: 從小到大!
try{ //try監控區域
//new Test().a();
if (b==0){// throw throws
throw new ArithmeticException();//主動拋出異常
}
System.out.println(a/b);
}catch (Error e){ //catch(想要捕獲的異常類型!) 捕獲異常
System.out.println("程序出現異常,變量b不能為0");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable e){
System.out.println("Throwable");
}finally { //處理善后工作
System.out.println("finally");
}
*/
/*
public void a(){
b();
}
public void b(){
a();
}
*/
package com.sj.exception;
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//command + option + T(mac)
//ctrl + alt + t(win)
try {
System.out.println(a/b);
} catch (Exception e) {
//System.exit(1); 主動結束程序
e.printStackTrace();//打印錯誤的棧信息
} finally {
}
}
}
5.自定義異常:
package com.sj.exception.demo02;
//自定義的異常類
public class MyException extends Exception{
//傳遞數字>10;
private int detail;
public MyException(int a) {
this.detail = a;
}
//toString:異常的打印信息
package com.sj.exception.demo02;
public class Test {
//可能會存在異常的方法
static void test(int a) throws MyException {
System.out.println("傳遞的參數為:"+ a);
if(a >10){
throw new MyException(a); //拋出
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
//增加一些處理異常的代碼塊~
System.out.println("Myexception=>"+e);
}
}
}
6.總結: