2016-08-15 70 views
-7

我很困惑,以便清楚地理解何時拋出和拋出被使用。請給我一個例子來展示它的不同之處。Java中的拋出和拋出的區別澄清

另外,我嘗試了下面的代碼:

package AccessModifiers;

// import java.io.IOException;

公共類ThrowExceptions {

int QAAutoLevel; 
int QAExp; 

void QAAutomationHiring(int grade) 
{ 
    if (grade<5) 
    throw new ArithmeticException("Not professionally Qualified"); 
    else 
     System.out.println("Ready to be test"); 

} 

void QAExperience(int x,int grade) 
{ 

     QAAutomationHiring(grade); 


} 

void checkThrowsExep(int a,int b) throws ArithmeticException 
{ 
    try{ 
    int result=a/b; 
    System.out.println("Result is :"+result); 
    } 
    catch(Exception e) 
    { 
     System.out.println("The error messgae is: "+ e.getMessage()); 
    } 
} 

public static void main(String args[]) 
{ 
    ThrowExceptions t=new ThrowExceptions(); 
    //t.QAAutomationHiring(8); 
    t.QAExperience(2,8); 
    t.QAExperience(4,2); 

    t.checkThrowsExep(5, 0); 

} 

}

在上面的代碼中,當我運行該程序,在主函數啉 't.checkThrowsExp' 未達到。我研究了throw和throws用於捕獲異常並繼續執行程序。但是這裏的執行停止了,並沒有繼續下一組陳述。請分享您的意見。

+1

當你想拋出異常時使用'throw'。 'throws'爲方法聲明瞭什麼潛在的'Exceptions'以便調用者知道要捕捉什麼。 – SomeJavaGuy

+3

請參見[Oracle Java教程 - 例外](https://docs.oracle.com/javase/tutorial/essential/exceptions/) – Jesper

回答

1

Throw實際上返回異常,而throws是編譯器的一個符號,該方法可能會返回一個異常。

在上面的代碼中,如果等級低於5,則會創建並返回異常ArithmeticException,這是您第二次調用QAExperience時的情況。 由於調用方法調用的方法返回了該異常,並不妨礙catch塊,它也將停止執行並返回主方法。由於主要方法也沒有捕捉到異常,它就像其他人一樣停止執行並返回異常。這就是爲什麼t.checkThrowsExp不會被執行的原因。

+0

非常感謝!我在main函數的QAExperience函數之前嘗試調用checkThrowsExp函數,並且顯示了ArithmeticException的消息。 – Vandee

+0

此外,我試着在QAAutomationHiring函數中添加try和catch塊來拋出異常。這將顯示異常消息並繼續執行下一步的語句。現在我明白了。 – Vandee

2

throws是用來告訴人們,

警告:此方法/構造函數拋出XXXExceptionYYYException的機會很高!請確保你處理它們!

例子:

Thread.sleep方法聲明爲:

public static native void sleep(long millis) throws InterruptedException; 

正如你所看到的,throws關鍵字告訴人們,sleep很可能會拋出一個InterruptedException。因此,您必須使用try-catch圍繞方法調用,或者使用throws InterruptedException標記調用方法。 throws關鍵字後的例外情況通常是由於程序的直接控制之外的區域中的無效條件(如無效的用戶輸入,數據庫問題等)導致的「檢查」異常。

請注意,方法標有throws XXXExcepion永不丟XXXException。另一方面,實際上引發異常。它可用於像

throw new RuntimeException("Something went wrong!"); 

每當執行代碼達到這一說法,則將會無論什麼拋出,並且該方法返回。

總之,throw實際上做投擲throws只有是一個例外可能會被拋出(這其實是錯誤的)。