gpt4 book ai didi

Java,默认异常消息

转载 作者:搜寻专家 更新时间:2023-11-01 01:16:29 26 4
gpt4 key购买 nike

鉴于以下情况:

public abstract class Test {
public static void main(String[] args) {
int[] testArray = {6, 3, 2};
System.out.println(testArray[3]);
}
}

当我运行程序时,我得到:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Test1.main(Test1.java:5)

在这种情况下,JVM 显示超出范围的索引,即 3。

抛开这个具体的例子,考虑到我选择不捕获程序代码中的异常:

  1. 对于任何已检查或未检查的异常,我如何找出 JVM 将显示的默认消息是什么?

  2. 对于我自己编写的自定义异常类,以及我在代码中使用“throw”关键字生成的此类对象(但同样选择不捕获),我是否可以设置JVM 将显示的默认消息?

最佳答案

  1. How can I found out, for any exception, either checked or unchecked, what the default message would be that the JVM would display?

正如您可能已经猜到的那样,答案是“一般来说,您不能”。大多数情况下,消息是从接受字符串消息的异常的构造函数之一设置的。如果幸运的话,该消息将很有意义并提供有用的信息。否则,按照惯例,异常的语义将主要存在于它的类名和相关的 Javadoc 中。还要考虑异常消息通常是本地化的。

  1. For a custom exception class that I write myself, and for an object of this class that I generate in my code using the 'throw' keyword (but, again, choose not to catch it), can I set up a default message that the JVM would display?

这完全取决于您。您可以像这样在默认构造函数中设置默认消息:

public class MyException extends Exception {
public MyException() {
super("my default message");
}

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

关于Java,默认异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30542846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com