簡體   English   中英

使用try和catch進行異常處理

[英]Exception handling with try and catch

創建類TestBook,並創建測試用例以測試類Book

在此階段不處理任何異常,只需將它們傳遞給調用方方法即可。

上面的指令是否意味着我的測試人員類TestBook應該具有其主方法“引發ParseException”,並且當我使用“錯誤”運行程序時不應崩潰,而是應將異常傳遞給...?

  public class TestBook{
       public static Book directory=new Book(); //Book contains an arraylist of dates

     public static void main(String[] args) throws ParseException {
                directory.addApt("01-04-1996","testdate"); 
           //this will create an instance of a  Apt and is in the INCORRECT format.
      }

Book類的addApt方法如下所示:

      String[] dates=date.split("-");
        if(dates[0]!=2)
            throw new ParseException("incorrect format day should be in numbers,2);
          if(dates[0]!=3)
            throw new ParseException("incorrect format month should be in letters,2);
          if(dates[0]!=4)
            throw new ParseException("incorrect format year should be in numbers,2);
        Apt newAppt=new Apt=(date,type);

當我運行此命令時,我收到一條錯誤消息:線程“ main”中的異常java.text.ParseException:格式錯誤,月份應以字母表示。

但是我的問題是,既然我扔了它,為什么會顯示出來,為什么要這樣處理呢? 我想我對投擲與嘗試/接球感到困惑。

似乎是要創建一個沒有main方法的TestBook類,但要使用其他測試Book類的static方法。 例如,您可能有一種方法來測試以正確格式創建書籍,一種方法來測試以錯誤格式創建書籍,等等。

沒有人可以捕捉/處理您拋出的異常,因此它一直冒泡到頂部,最終被打印出來。 您期望發生什么?

throw異常。 如果您想自己處理它,則需要將其catch在某處...

throw exception 關鍵字允許您引發自己的自定義異常。

所有未處理的異常(自定義或標准)都將導致運行時異常。

將調用addApt方法的代碼放在try/catch塊中,並catchthrowingexceptions


拋出異常是一種擺脫帶有非空返回類型的方法返回值的好方法。 對於一個非常簡單的示例,假設我們有一個名為public int getDaysInMonth(int month) 現在,我們預計month為1到12。 而且我們的方法必須返回一個int。 那么,當方法以無效月份被調用時,我們該怎么辦?

int getDaysInMonth(int month) {
    switch(month) {
        //case 1-12
        default:
            break;
    }
}

所以...我們可以為所有有效月份提供一個案例,這不是問題。 一種解決方案可能是返回0-1或返回明顯的值。 但是我們實際上根本不需要返回任何東西。 我們可以拋出一個異常。

default:
    throw new IllegalArgumentException("Month must be between 1 and 12");

現在,我們getDaysInMonth(int)調用放在try/catch塊中,否則,我們的程序可能會因非法參數異常而停止。 但是我們可以將邏輯放在catch塊中,以處理如何處理此異常等。

我知道我的示例並不是根據您的情況建模的,但是它是如何充分利用throw的一個很好的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM