1. 程式人生 > >07-異常處理

07-異常處理

hello about nds else if 成績 tof dialog scan 不一定

技術分享

技術分享

package 測試;
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");
     }
  }
}

  

技術分享

技術分享

技術分享

技術分享

ArrayIndexOutOfBoundsException/內層try-catch

發生ArithmeticException

技術分享

技術分享

ArrayIndexOutOfBoundsException/外層try-catch

技術分享

技術分享

當try不出錯時,只運行finally

技術分享

技術分享

finally語句塊不一定會執行,當Try語句中throw一個錯誤時fin被catch語句截獲,並在catch語句中有exit(0)時,finally語句不會被執行。

技術分享

package 考試成績;
import java.util.Scanner;
// 陳天時 20163591 信1605-3
public class KaoShiChengJi 
{
	public static void main(String[] args)
    {
		@SuppressWarnings("resource")
		Scanner input=new Scanner(System.in);
        for(;;)//無限循環
        {
        	System.out.println("請輸入一門考試的成績:");
    		String I=input.next();
    		int i=Integer.parseInt(I);
            try
            {

                if(i>0&&i<60)
                {
                	System.out.println("不及格");
                	continue;//跳出循環
                }
                else if(i>=60&&i<70)
                {
                	System.out.println("及格");
                	continue;
                }
                else if(i>=70&&i<80)
                {
                	System.out.println("中");
                	continue;
                }
                else if(i>=80&&i<90)
                {
                	System.out.println("良");
                	continue;
                }
                else if(i>=90&&i<=100)
                {
                	System.out.println("優");
                    continue;
                }
                else 
                {
                	System.out.println("您輸入的成績超出範圍,請重新輸入!");
                }
            }
            catch(NumberFormatException e)
            {
            	System.out.println("您輸入的成績超出範圍,請重新輸入!");
            }
            continue;
        }
    }
}

07-異常處理