3
$ 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

コード

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() );
        }
    }
}
4

2 に答える 2

6

TestExceptions.testtype を返すvoidので、それはできませんthrow。これが機能するには、拡張する型のオブジェクトを返す必要がありますThrowable

一例は次のとおりです。

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

ただし、これはあまりきれいではありません。より良いパターンは、 or を拡張するクラスを定義し、それTestExceptionを拡張することです。ExceptionRuntimeExceptionThrowablethrow

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。)

于 2010-04-13T16:37:08.743 に答える
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メッセージで のスーパークラス コンストラクターを呼び出さない

投稿されたコードは、これらの問題を解決し、期待どおりのものを表示します。

于 2010-04-13T16:38:48.613 に答える