java 类中自定义异常,如何在Java中定义自定义异常类,最简单的方法是什么?

博客内容讲述了在Java中创建自定义异常类时遇到的问题。作者尝试定义一个继承自Exception的MyException类,并在Foo类的bar方法中抛出这个异常。然而,Java编译器报错,提示找不到带String参数的构造函数。解决方案是需要在MyException类中定义一个接受String参数的构造函数,并通过super(message)调用父类的构造函数。
摘要由CSDN通过智能技术生成

I'm trying to define my own exception class the easiest way, and this is what I'm getting:

public class MyException extends Exception {}

public class Foo {

public bar() throws MyException {

throw new MyException("try again please");

}

}

This is what Java compiler says:

cannot find symbol: constructor MyException(java.lang.String)

I had a feeling that this constructor has to be inherited from java.lang.Exception, isn't it?

解决方案

No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message) in your constructor to invoke your parent constructor. For example, like this:

public class MyException extends Exception {

public MyException(String message) {

super(message);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值