自定義例外
package com.andy.base.exception.demo01.demo02;
//自定義的例外類
public class MyException extends Exception {
//傳遞數字>10;
private int detail;
public MyException(int a ){
this.detail = a;
}
//toString 列印
@Override
public String toString() {
return "MyException{" + detail + '}';
}
}
package com.andy.base.exception.demo01.demo02;
public class Test {
//可能會存在的例外的方法
static void test(int a) throws MyException {
System.out.println("傳遞的引數為:"+ a);
if(a>10){
throw new MyException(a); //alt+enter
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
//e.printStackTrace();
//這里可以寫一些處理例外的代碼~~
System.out.println("MyException=>"+e);
}
}
}
Note
實際應用中的經驗總結:
1.處理運行的例外時,采用邏輯去合理規避同時輔助try-catch處理
2.在多重catch塊后面,可以加一個catch(Exception)來處理可能會被遺漏的例外
3.對于不確定的代碼,也可以加上try-catch,處理潛在的例外
4.盡量去處理例外,切忌只是簡單地呼叫printStackTrac()去列印輸出
5.具體如何處理例外,要根據不同的業務需求和例外型別去決定
6.盡量添加finally陳述句塊去釋放占用的資源
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/545305.html
標籤:其他
