Java:自定义异常错误

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() );
        }
    }
}
2个回答

6

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

那是因为String不是Throwable。请看我的回答的第二句话。 - danben

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的超类构造函数

发布的代码已解决这些问题并显示了你所期望的结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接