2010-04-13 52 views
2
$ javac TestExceptions.java 
TestExceptions.java:11: cannot find symbol 
symbol : class test 
location: class TestExceptions 
      throw new TestExceptions.test("If you see me, exceptions work!"); 
            ^
1 error 

代碼的Java:定製異常錯誤

import java.util.*; 
import java.io.*; 

public class TestExceptions { 
    static void test(String message) throws java.lang.Error{ 
     System.out.println(message); 
    } 

    public static void main(String[] args){ 
     try { 
      // Why does it not access TestExceptions.test-method in the class? 
      throw new TestExceptions.test("If you see me, exceptions work!"); 
     }catch(java.lang.Error a){ 
      System.out.println("Working Status: " + a.getMessage()); 
     } 
    } 
} 

回答

3

工作代碼

試試這個:

public class TestExceptions extends Exception { 
    public TestExceptions(String s) { 
     super(s); 
    } 

    public static void main(String[] args) throws TestExceptions{ 
     try { 
      throw new TestExceptions("If you see me, exceptions work!"); 
     } 
     catch(Exception a) { 
      System.out.println("Working Status: " + a.getMessage()); 
     } 
    } 
} 

問題

有許多與代碼問題您發佈,包括:

  • 追趕Error代替Exception
  • 使用一個靜態方法來構造異常
  • 不延長Exception您的異常
  • 未調用Exception的超類構造函數,並顯示消息

發佈的代碼可以解決這些問題並顯示您的期望。

4

TestExceptions.test返回類型爲void,所以你不能throw它。爲此,它需要返回一個類型爲Throwable的對象。

一個例子是:

static Exception test(String message) { 
     return new Exception(message); 
    } 

然而,這是不是很乾淨。更好的模式是定義一個TestException類,它繼承ExceptionRuntimeExceptionThrowable,然後就是throw

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

// somewhere else 
public static void main(String[] args) throws TestException{ 
    try { 
     throw new TestException("If you see me, exceptions work!"); 
    }catch(Exception a){ 
     System.out.println("Working Status: " + a.getMessage()); 
    } 
} 

(另請注意,在包java.lang所有類可以通過其類名,而不是其完全限定名稱被引用。也就是說,你不需要寫java.lang

+0

當將返回類型改爲String時,我得到了同樣的錯誤。 – hhh 2010-04-13 16:38:58

+0

這是因爲'String'不是'Throwable'。看到我答案的第二句話。 – danben 2010-04-13 16:39:14