Java:自定义异常错误
代码Java:自定义异常错误,java,error-handling,custom-errors,Java,Error Handling,Custom Errors,代码 $ 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
$ 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
TestExceptions.test
返回类型void
,因此不能抛出它。要使其工作,它需要返回一个扩展了Throwable
类型的对象
一个例子可能是:
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() );
}
}
}
然而,这不是很干净。更好的模式是定义一个扩展Exception
或RuntimeException
或Throwable
的TestException
类,然后只定义throw
static Exception test(String message) {
return new Exception(message);
}
(还要注意,包java.lang
中的所有类都可以通过它们的类名而不是它们的完全限定名来引用。也就是说,您不需要编写java.lang
)工作代码
$ 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
试试这个:
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() );
}
}
问题
您发布的代码存在许多问题,包括:
- 捕获
错误
而不是异常
- 使用静态方法构造异常
- 不为您的异常扩展
异常
- 不使用消息调用异常的超类构造函数
发布的代码解决了这些问题,并显示了您所期望的内容。这是因为String
不是Throwable
。见我答案的第二句。