Java異常處理運行時異常(RuntimeException)詳解及實例
RuntimeException
RunntimeException的子類:
ClassCastException
多態中,可以使用Instanceof 判斷,進行規避
ArithmeticException
進行if判斷,如果除數為0,進行return
NullPointerException
進行if判斷,是否為null
ArrayIndexOutOfBoundsException
使用數組length屬性,避免越界
這些異常時可以通過程序員的良好編程習慣進行避免的
1:遇到運行時異常無需進行處理,直接找到出現問題的代碼,進行規避。
2:就像人上火一樣牙疼一樣,找到原因,自行解決即可
3:該種異常編譯器不會檢查程序員是否處理該異常
4:如果是運行時異常,那么沒有必要在函數上進行聲明。
案例
1:除法運算功能(div(int x,int y))
2:if判斷如果除數為0,throw new ArithmeticException();
3:函數聲明throws ArithmeticException
4:main方法調用div,不進行處理
5:編譯通過,運行正常
6:如果除數為0,報異常,程序停止。
7:如果是運行時異常,那么沒有必要在函數上進行聲明。
1:Object類中的wait()方法,內部throw了2個異常 IllegalMonitorStateException InterruptedException
1:只聲明了一個(throws) IllegalMonitorStateException是運行是異常沒有聲明。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Demo{ public static void main(String[] args){ div( 2 , 1 ); } public static void div( int x, int y) { if (y == 0 ) { throw new ArithmeticException(); } System.out.println(x / y); } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!