2014-03-31 56 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