1. 程式人生 > 實用技巧 >2020.10.27收穫+動手動腦六

2020.10.27收穫+動手動腦六

*****************************************************************藍色粗體為動手動腦*********************************************************************************

異常處理

1.Java異常處理基礎

異常:發生於程式執行期間,表明出現了一個非法的執行狀況。許多哦JDK中的方法在檢測到非法情況時,都會丟擲一個異常物件。

例如:陣列越界和被零除

AboutException.java

import javax.swing.*;

class AboutException {
   public static void main(String[] a) 
   {
      int i=1, j=0, k;
      k=i/j;


	try
	{
		
		k = i/j;    // Causes division-by-zero exception
		//throw new Exception("Hello.Exception!");
	}
	
	catch ( ArithmeticException e)  //捕獲算術異常
	{
		System.out.println("被0除.  "+ e.getMessage());
	}
	
	catch (Exception e)
	{
		if (e instanceof ArithmeticException)
			System.out.println("被0除");
		else
		{  
			System.out.println(e.getMessage());
			
		}
	}
	
	finally
     	{
     		JOptionPane.showConfirmDialog(null,"OK");
     	}		
  }
}

  

2.受控“(check)”的異常

3.自定義異常與異常處理鏈