2019年8月25日 星期日

[Java程式]_Ch12.3_設計Java未知例外



歡迎訂閱頻道:杜仲教學YouTube
https://www.youtube.com/channel/UCElwt6s8Ea_V-gnu9sZZT5g?sub_confirmation=1
杜仲教學部落格:
https://derekcctu.blogspot.com/

1 則留言:

  1. class 數值為負數例外 extends Exception{}
    class 數值為零例外 extends Exception{}
    class CTest{
    int num;
    public void compute(int a,int b,int n)throws ArithmeticException,ArrayIndexOutOfBoundsException{
    if(b==0)
    throw new ArithmeticException();
    else
    System.out.println(a+"/"+b+"="+(a/b));
    int A[]=new int[5];
    if(n>=A.length)
    throw new ArrayIndexOutOfBoundsException();
    else
    A[n]=99999;
    System.out.println("A["+n+"]="+A[n]);
    }
    public void setNum(int num)throws 數值為負數例外,數值為零例外{
    if(num==0)
    throw new 數值為零例外();
    else if(num<0)
    throw new 數值為負數例外();
    else
    this.num=num;
    System.out.println("num="+this.num);
    }
    }
    public class A12
    {
    public static void main(String args[])
    {
    int A[]=new int[5];
    try{
    A[10]=100;
    }catch(Exception e){
    A[0]=100;
    System.out.println("1.[Catch]例外發生,A[0]="+A[0]+" e="+e);
    }finally{
    System.out.println("[Finally]粉身碎骨都要做!");
    }
    int a=155,b=0;
    try{
    if(b==0)
    throw new ArithmeticException();
    else
    System.out.println(a+"/"+b+"="+(a/b));
    }catch(ArithmeticException e){
    System.out.println("2.[Catch]例外發生, e="+e);
    }
    CTest c1=new CTest();
    try{
    c1.compute(5, 1, 10);
    }catch(ArithmeticException | ArrayIndexOutOfBoundsException e){
    System.out.println("3.[Catch]例外發生, e="+e);
    }

    try {
    c1.setNum(0);
    } catch (數值為負數例外 e) {
    System.out.println("4.[Catch]例外發生, e="+e);
    } catch (數值為零例外 e) {
    System.out.println("5.[Catch]例外發生, e="+e);
    }


    System.out.println("主程式結束...A[0]="+A[0]);
    }
    }

    回覆刪除

Ether.fi Cash Card 一張所有人必備的加密貨幣信用卡   [Ether.fi Cash Card] : https://www.ether.fi/app/cash/sign-up?ref_code=d27f8523 ------國際交易所------ [Bitg...