2014-03-05 25 views
-1

如何制定自定義異常以確定字符串!= 1? 到目前爲止,這是我的,但我不確定它是否接近正確。Java中的字符串自定義異常

我想編寫一個紙牌遊戲,我想拋出一個例外

if (rank.length() != 1) { 
     return; 
    } 

所以,我想有該例外。

public class StringLengthException extends Exception{ 


    public StringLengthException() {} 


    public StringLengthException (String message) 
    { 
    super(message); 
    } 

} 

這裏是我嘗試寫

/** 
* Name mutator. 
* 
* Business rules: - should be in the range A, 1, ..., 9, T, J, Q, K 
* 
* @param rank the rank to set 
*/ 
public void setRank(String rank) { 
    // make sure the rank isn't null 
    if (rank == null) { 
     throw new NullPointerException ("Rank is null"); 
    } 
    // make sure the rank isn't too long or too short 
    if (rank.length() != 1) { 
     return; 
    } 
    rank = rank.toUpperCase(); 
    // check if the rank is one of the allowed ones 
    if ("A23456789TJQK".contains(rank)) { 
     this.rank = rank; 
     // is this an ace? 
     if (rank.equals(ACE)) { 
      this.value = 1; 
     } else // perhaps it is a face card? 
     if ((TEN + JACK + QUEEN + KING).contains(rank)) { 
      this.value = 10; 
     } else { 
      // it must be a regular card 
      this.value = Integer.parseInt(rank); 
     } 
    } 
} 
+0

你在找'IllegalArgumentException'嗎? –

+0

檢查上面的編輯 – user3382217

回答

1

異常你可以做的是檢查字符串的長度等於1,如果是的話,拋出異常類:

String str = "..."; 

if (str.length() == 1) 
    throw new StringLengthException(); 

你必須把這個,在方法內部:

public void someOperationWithStrings(String str) throws StringLengthException { 
    if (str.length() == 1) 
     throw new StringLengthException(); 
} 

不要忘記,如果拋出一個方法內的異常,你必須聲明方法拋出異常

0

發生異常情況時會引發異常。在某些操作正在進行時,您需要計算出異常情況。像你的情況,字符串長度不等於1 所以,你的代碼應該是這樣的:

if (yourstring.length != 1){ 
    throw new StringLengthException(); 
    } 

而且異常應包含消息,所以事業的識別變得更容易。

if (yourstring.length != 1){ 
    throw new StringLengthException("String length is not equal to 1: String is:" + yourstring); 
    } 
0

你的類是很好的,你現在要做的唯一事情就是使用它:

public void doSomething (String rank) throws StringLengthException { 
    if (rank.length()!=1) 
     throw new StringLengthException("rank is not of size 1"); 

    // Do stuff 
} 

並調用這樣的方法:

try { 
    String rank = "A"; 
    doSomething(rank); 
} catch (StringLengthException sle) { 
    sle.printStackTrace(); 
} 

但是,如果你想要存儲一個字符,爲什麼不使用Characterchar類型?