2014-03-31 138 views
1

我正在研究Java中的Sudoku求解器,作爲有趣的語言介紹。我有我的代碼做的事情之一是檢查是否解決難題之前,它試圖解決它。我認爲這是一個好主意,使用try{}catch{}這個,但我不能得到編譯代碼。嘗試在Java中捕獲

public class SudokuSolver2 
{ 
    public static void main(String[] args) { 
     // 9x9 integer array with currentPuzzle 

     // check current puzzle and make sure it is a legal puzzle, else throw "illegal puzzle" error 
     try 
     { 
      // 1) check each row and make sure there is only 1 number per row 
      // 2) check each column and make sure there is only 1 number per column 
      // 3) check each square and make sure there is only 1 number per square 

      throw new illegalPuzzle(""); 
     } 
     catch (illegalPuzzle(String e)) 
     { 
      System.out.println("Illegal puzzle."); 
      System.exit(1); 
     } 
    } 
} 

public class illegalPuzzle extends Exception 
{ 
    public illegalPuzzle(String message) 
    { 
     super(message); 
    } 
} 

的問題,夫婦......

  1. 爲什麼不代碼編譯目前的形式?

  2. 有沒有辦法編寫代碼,以便我不必使用「String message」參數?我看到的所有示例都使用字符串參數,但我並不真正需要它或需要它。

  3. 有沒有辦法編寫代碼,以便我不必創建自己的自定義異常類?換句話說,我能拋出一個普遍的錯誤嗎?我看到的所有示例都創建了自己的自定義異常,但我不需要那麼詳細。

謝謝!

+1

類應以大寫首字母來命名,這樣反而IllegalPuzzle illegalPuzzle。 –

回答

2

答案1.代碼將無法以目前的形式編寫,使你的catch子句應寫成如下:

catch (illegalPuzzle e) 
{ 
    System.out.println("Illegal puzzle."); 
    System.exit(1); 
} 

回答2.只要將Exception(基類的所有異常)的你的嘗試,並刪除illegalPuzzle類。這是如何:

public class SudokuSolver 
{ 
    public static void main(String[] args) 
    { 
    try 
    { 
     // other statements 
     throw new Exception(); 
    } 
    catch (Exception e) 
    { 
     System.out.println("Illegal puzzle."); 
     System.exit(1); 
    } 
    } 
} 

答案3.答案2也回答這部分以及。

1

跟着你身材秀try catch塊

enter image description here

嘗試的流動,

try{ 
     throw new Exception("IllegalPuzzleException"); 
}catch (Exception e){ 
    System.out.println(e.getMessage()); 
} 
0

請儘量拋出特定異常的非法拼圖異常和捕捉其他異常另一個代碼塊可能被代碼的其他部分拋出。

public static void main(String args[]) { 
    try { 
     throw new IllegalPuzzle("Illegal Puzzle"); 
    } catch (IllegalPuzzle e) { 
     System.out.println(e.getMessage()); 
     System.exit(1); 
    } catch (Exception ex) { 
     System.out.println("Inside Exception: " + ex.getMessage()); 
    } 
} 

也請看看下面連寫拋出代碼之前:Throwing exceptions in Java