有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java应该覆盖哪个异常方法?

我有一个自己的异常,即InputException

当它没有被捕获时,JVM会写入控制台堆栈跟踪

public static void main(String[] args) throws InputException{
    throw new InputException();
}

JVM写入控制台

线程“main”InputException中的异常 在测试中。主要的main(main.java:8)

如何更改此消息,InputException的哪个方法生成此stackTrace


共 (5) 个答案

  1. # 1 楼答案

    重载InputException的构造函数

    public InputException(String message) {
        super(message);
    }
    

    然后使用它

    throw new InputException("an input exception has occurred");
    
  2. # 2 楼答案

    throw new InputException("your message here");
    

    因此,您必须在exception类中创建一个使用字符串参数调用super的构造函数:

    public class InputException extends Exception {
        public InputException(String message) {
            super(message);
        }
    }
    

    控制台上打印的消息是getMessage()方法返回的消息,默认情况下返回传递给Throwable构造函数的消息

  3. # 3 楼答案

    可以用应该打印的消息重载Exception构造函数,例如

    public InputException(String message) {
        super(message);
    }
    

    然后抛出异常,如下所示:

    throw new InputException("message");
    

    请看一看Java documentation关于我们为什么可以这样做

  4. # 4 楼答案

    JVM在内部调用printStackTrace()方法(因为您没有重写它,所以将调用Throwable类实现)
    根据Throwable#printStackTrace

    The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace()

    如果不需要这种表示,那么可以在自定义异常类中重写printStackTrace()方法,或者在创建其对象时将字符串消息作为构造函数参数传递

  5. # 5 楼答案

    恐怕没有办法改变

    相反,您可能希望捕获异常,处理它,并将一些整洁的消息输出到控制台(或记录器)