当前位置: 动力学知识库 > 问答 > 编程问答 >

exception handling - RuntimeException Extension in Java

问题描述:

I have simply added an extension to the EmptyStackException in Java to show an error message. I have put this file under the same package, but I get the error:

"The constructor EmptyStackException(String) is undefined"

EmptyStackException.java:

package mypackage;

public class EmptyStackException extends RuntimeException{

private static final long serialVersionUID = 1L;

public EmptyStackException(String message){

super(message);

}

}

Should be something very simple. But I got stuck!

Any help is appreciated.

网友答案:

You have defined your own EmptyStackException, but Java supplies java.util.EmptyStackException, and its only constructor takes no arguments, which means your code that you think uses your own EmptyStackException actually is using java.util.EmptyStackException.

To extend EmptyStackException, define your own:

public MyEmptyStackExceptionWithMessage extends EmptyStackException {

In the constructor, call super() and store your own message.

网友答案:

It looks like you're trying to replace the existing EmptyStackException class with one of your own; this is always a very bad idea (and in many Java environments, not possible.) Probably the compile error is arising because although you're trying to construct an instance of your class, the Java compiler is actually trying to instantiate java.util.EmptyStackException which indeed has no one-argument constructor. Basically, if you need to define your own exception types, choose names that aren't already used by a platform class -- you'll avoid a lot of hassle. And if your goal is truly to replace the Java API class: give up. It's not going to happen.

分享给朋友:
您可能感兴趣的文章:
随机阅读: