What is an easy way to create an exception handling class in Java?

Asked 2 years ago, Updated 2 years ago, 99 views

You are about to create an exception handling class.

public class MyException extends Exception {}

public class Foo {
  public bar() throws MyException {
    throw new MyException("try again please");
  }
}

I tried it like this. In the compiler, cannot find symbol: constructor MyException(java.lang.String) There's an error like this. But isn't the constructor inherited from java.lang.Exception?

java exception inheritance

2022-09-21 18:06

1 Answers

The constructor must be newly defined. And you have to call super (message) in the constructor to include the parent constructor. For example,

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

You have to do it like this.


2022-09-21 18:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.