gpt4 book ai didi

java - Java 中 EmptyStackException 的自定义错误消息?

转载 作者:行者123 更新时间:2023-11-30 02:23:03 25 4
gpt4 key购买 nike

我正在用 Java 实现 Stack。对于 pop 操作,我想抛出 EmptyStackException。根据documentationEmptyStackException 有一个构造函数,EmptyStackException()。它 -

Constructs a new EmptyStackException with null as its error message string.

所以它不能将我的自定义错误消息作为参数。我需要设置自定义错误消息,因为它的错误消息为 null 并且 getMessage() 返回 null。如果我使用此异常,我必须在捕获 EmptyStackException 的位置对错误消息进行硬编码。

public int pop() {
if (empty())
throw new EmptyStackException(); // cannot take error message as argument
int data = top.getData();
top = top.getNext();
return data;
}
public static void main(String[] args) {
Stack stack = new Stack();
try {
System.out.println(stack.pop());
} catch (EmptyStackException e) {
System.out.println("Stack is empty"); // my hardcoded message
}

另一种方法是使用Exception而不是EmptyStackException。它有一个构造函数:Exception(String message)。使用它,我可以设置我的自定义消息。

public int pop() throws Exception {
if (empty())
throw new Exception("Stack is empty"); // take message as argument
int data = top.getData();
top = top.getNext();
return data;
}
public static void main(String[] args) {
Stack stack = new Stack();
try {
System.out.println(stack.pop());
} catch (Exception e) {
System.out.println(e.getMessage()); //print message set from the throwing position
}

我的问题是,哪种方法是最佳实践,或者还有其他方法吗?

最佳答案

EmptyStackException 类是 self 解释的。认为不需要任何其他消息。我会保持原样:)。如果您仍然需要消息,那么创建自定义异常类是广泛使用的方法。

关于java - Java 中 EmptyStackException 的自定义错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46319979/

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