java 自定义异常中的超级调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13908413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Super call in custom exception
提问by Java_Alert
I just want to know why we call super in own created custom exception.
我只想知道为什么我们在自己创建的自定义异常中调用 super 。
public class MyException extends Exception
{
public MyException(String message)
{
super(message);
}
}
Here What is the use of calling super(message)
这里调用super(message)有什么用
回答by Platinum Azure
Since a derived class always has the base class as a template, it is necessary to initialize the base class as the first step in constructing the derived object. By default, if no super
call is made, Java will use a default (parameterless) constructor to create the base class. If you want a different constructor to be used, you have to use super
to pass in the parameters you want and invoke the correct constructor.
由于派生类总是以基类为模板,因此在构造派生对象时,首先需要对基类进行初始化。默认情况下,如果没有super
调用,Java 将使用默认(无参数)构造函数来创建基类。如果要使用不同的构造函数,则必须使用super
传入所需的参数并调用正确的构造函数。
In the case of custom exceptions, it is common to use super
to initialize the exception's error message; by passing the message into the base class constructor, the base class will take care of the work of setting the message up correctly.
在自定义异常的情况下,通常使用super
初始化异常的错误信息;通过将消息传递给基类构造函数,基类将负责正确设置消息的工作。
回答by Luchian Grigore
It's just calling the base class constructor:
它只是调用基类构造函数:
Exception(String message)
Constructs a new exception with the specified detail message.
Exception(String message)
构造具有指定详细消息的新异常。
回答by Usman Saleem
Because:
因为:
public MyException(String message)
{
//super() implicit call, how to set message???
}
So you need a super(message) call to set the message.
所以你需要一个 super(message) 调用来设置消息。
回答by codeMan
The use of super is to call the constructor of the super(base, parent) class which happens to be the Exception
class
super的用途是调用super(base, parent)类的构造函数,正好是Exception
类