简体   繁体   English

引发自定义Java异常

[英]Throwing custom Java exceptions

I am working on a homework assignment for a Java Data Structures class, and we have to build a program from a stack ADT using a linked list implementation. 我正在为Java数据结构类进行作业分配,我们必须使用链接列表实现从堆栈ADT构建程序。 The professor has requested that we include a method called popTop() which pops the top element of the stack, and throws a "StackUnderflowException" if the stack is empty. 教授要求我们包含一个名为popTop()的方法,该方法弹出堆栈的顶部元素,如果堆栈为空,则抛出“ StackUnderflowException”。 From what I can gather this is an exception class that we have to write ourselves, and I am having some problems with it. 据我所知,这是一个我们必须自己编写的异常类,我对此有一些疑问。 If anyone could help me I would be extremely appreciative. 如果有人可以帮助我,我将非常感激。 Here is some of my code: 这是我的一些代码:

private class StackUnderflowException extends RuntimeException {

    public StackUnderflowException() {
        super("Cannot pop the top, stack is empty");
    }
    public StackUnderflowException(String message) {
        super(message);
    }
}

That's the exception class I wrote, here is the beginning of the popTop() method that I have written thus far: 那是我编写的异常类,这是到目前为止我编写的popTop()方法的开头:

public T popTop() throws StackUnderflowException {
    if (sz <= 0) {
        throw new StackUnderflowException();
    }
}

I am getting errors suggesting that StackUnderflowException cannot be a subclass of RuntimeException, could anyone shed some more light on this? 我收到错误消息,提示StackUnderflowException不能是RuntimeException的子类,有人可以对此进行更多说明吗? And within the method I'm getting errors saying StackUnderflowException is undefined. 在方法中,我收到错误消息,说未定义StackUnderflowException。

您的构造函数是私有的,应该扩展Exception而不是RuntimeException

There are 2 problems with your code 1.Your customised Exception class is private 2. It extends runtime exception where it should be entensing the superclass Exception 您的代码有2个问题1.您自定义的Exception类是私有的2.它在应增强超类Exception的地方扩展了运行时异常

You can create custom exception as is given below: 您可以创建自定义异常,如下所示:

public class StackUnderflowException extends Exception{ 公共类StackUnderflowException扩展了异常{

private static final long serialVersionUID = 1L;

/**
 * Default constructor.
 */
public StackUnderflowException(){

}
/**
 * The constructor wraps the exception thrown in a method.
 * @param e the exception instance.
 */
public StackUnderflowException( Throwable e) 
{
    super(e);
}
/**
 * The constructor wraps the exception and the message thrown in a method.
 * @param msg the exception instance.
 * @param e the exception message.
 */
public StackUnderflowException(String msg, Throwable e) 
{
    super(msg, e);

}

/**
 * The constructor initializes the exception message.
 * @param msg the exception message 
 */
public StackUnderflowException(String msg) 
{
    super(msg);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM