Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:自定义异常错误_Java_Error Handling_Custom Errors - Fatal编程技术网

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
。见我答案的第二句。