Java:自定义异常错误

hhh*_*hhh 2 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
Run Code Online (Sandbox Code Playgroud)

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() );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

dan*_*ben 5

TestExceptions.test返回类型void,所以你不能throw.为此,它需要返回一个扩展类型的对象Throwable.

一个例子可能是:

   static Exception test(String message) {
        return new Exception(message);
    } 
Run Code Online (Sandbox Code Playgroud)

但是,这不是很干净.更好的方式是定义一个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() );
    }
}
Run Code Online (Sandbox Code Playgroud)

(另请注意,包中的所有类java.lang都可以通过其类名而不是完全限定名来引用.也就是说,您不需要编写java.lang.)