2013-07-10 88 views
-3

在Java中,僅用於投擲您已經創建例外關鍵字(擲)。如果沒有,有人給它是如何使用自己的例外之外的例子。throw關鍵字在Java中

+1

任何異常'拋出新拋出:IllegalArgumentException( 「什麼」);' – CPerkins

+3

http://docs.oracle.com/javase/tutorial/essential/例外/ –

+1

如何可以在JVM可能知道是誰創建的異常類?問題沒有意義。 – EJP

回答

3

您可以throw任何擴展Throwable

void greet(String name) { 
    if (name == null) { 
     throw new IllegalArgumentException("Cannot greet null"); 
    } 
    System.out.println("Hello, " + name); 
} 
1

沒有,throw關鍵字可以任何Exception,包括內置的人使用:

throw new IllegalArgumentException("Your value passed in was illegal"); 
+0

@Downvoter爲什麼downvote? – rgettman

2

如上面所提到的JLS 14.18

The Expression in a throw statement must denote either 1) a variable or value of a reference type which is assignable (§5.2) to the type Throwable, or 2) the null reference, or a compile-time error occurs.

例如,考慮情況如下:

public void factorial(int num) 
{ 
    if (num < 0) 
    { 
     throw new IllegalArgumentException("Invalid number :"+num); 
    } 
    else 
     //....code for factorial. 
} 

這裏IllegalArgumentException不是用戶定義的異常。它是一種建立在RunTimeException和在Oracle文檔規定:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

1

你可以扔東西延伸Throwable包括錯誤,你的異常,和Java內置例外。

它也可以用於更復雜的邏輯:

你可以用它來其他異常中重新拋出,例如,ThreadDeathErrors。當一個線程必須死,它可以捕捉這個錯誤:

catch(ThreadDeathError e){ 
    System.out.println("Thread going down"); 
    throw e; 
} 

這裏,e是不是你自己的異常,但被抓住了一個錯誤。請尊重錯誤和例外之間的差異,因爲前者通常不會被捕獲。必須重新拋出

線程死亡的錯誤實際上導致theread死亡。

0

投可用於thow擴展java.lang.Throwable的