自定义异常中的超级调用 [英] Super call in custom exception

查看:53
本文介绍了自定义异常中的超级调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道为什么我们在自己创建的自定义异常中调用super。

I just want to know why we call super in own created custom exception.

public class MyException extends Exception 
{ 
   public MyException(String message)         
  {  
    super(message);        
  }      
}

这里调用super(消息)的用途是什么

Here What is the use of calling super(message)

推荐答案

由于派生类始终将基类作为模板,因此第一步需要初始化基类在构造派生对象时。默认情况下,如果没有进行 super 调用,Java将使用默认(无参数)构造函数创建基类。如果要使用其他构造函数,则必须使用 super 传递所需的参数并调用正确的构造函数。

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 初始化异常的错误消息;通过将消息传递给基类构造函数,基类将负责正确设置消息的工作。

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.

这篇关于自定义异常中的超级调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆