1

I would like to have several custom errors in my code (extending RuntimeException), however it seems that I need to write out the same code each time - can this be done without so much repetition?

For example, in the following code, if I wanted to also make an underflow error, or maybe some more errors, would I have to copy & paste this code replacing 'OverflowError' with whatever I want the new exception to be called? Is there any way of making this 'dryer'?

class OverflowError extends RuntimeException {
    private static final long serialVersionUID = 1L; //VS Code says I need it and I don't know what this line does, but that's another question for another day

    public OverlowError(String message) {
        super(message);
    }
}

It seems that if I extend RuntimeException with no code inside, it doesn't inherit the constructor and therefore will not work because of unexpected arguments.

Doot
  • 555
  • 5
  • 15
  • 2
    Most IDEs can generate these Exception classes. Please do not call an Exception something "Error", because in Java this means they are _not_ regular exceptions (e.g. `OutOfMemoryError` is not a class derived from `Exception`!) The `serialVersionUID` is only needed if the Exception is going to be serialized and read back later with potential changes to the code/classes in between. Fix the IDE if it annoys you, but adding it to the code without any serializazion in place can surely be confusing for your code's readers. – linux-fan Nov 04 '19 at 22:05
  • You do need to redeclare your constructor in every subclass. So you basically do need roughly this code for every new class. You don't necessarily need the serialVersionUID. – khelwood Nov 04 '19 at 22:07
  • 2
    The IDE's will just generate the same thing here... which would be the same result as you copying and pasting... what is the need for your custom exceptions? Usually there's a better way to deal with errors than creating a custom exception for each one – RobOhRob Nov 04 '19 at 22:07
  • If you have 100s of such classes, it can get a bit boring/tedious to even use IDE to generate those as others have said. Maybe you can take a look at reflection and then simply have a map of String,String where key is className, and value is the message with which you want your class constructor to be called. Check this link for starters. https://stackoverflow.com/questions/7495785/java-how-to-instantiate-a-class-from-string – theprogrammer Nov 05 '19 at 03:29

0 Answers0