2

There is a lot out there on how you can't override exception constructors and how to do custom exceptions, but I haven't been able to find anything on disabling a constructor for an extended class.

I've created a custom class that coworkers are (basically) using as the original Exception class. As a counter measure, I wanted to override the constructors to throw an exception to prevent them from misusing the custom exception.

However, one cannot override Exception constructors.

Is there a way to disable them or get an equivalent behavior to prevent people from constructing my custom exception except how I want them to?

0

1 Answer 1

4

The right way to fix this is to make your constructor private. That should ensure that nobody can use it. For example:

public class MyCustomException extends Exception {
   private MyCustomException() {
     //Nah Nah Nah, now you can't construct me from outside anymore
   }
}
3
  • One caveat, though certainly an edge case, is that you could still deserialize an instance.
    – Adrian Larson
    Commented Jul 9, 2019 at 22:00
  • True. Though in the OP's use-case I suspect that will be harder than just using the right constructor. Commented Jul 9, 2019 at 22:01
  • 1
    Gave this a shot, but I still get: -System exception constructor already defined: void <init>()- It looks like making it private is still a version of overriding the Exception constructor. :( Thanks though.
    – Kamurai
    Commented Jul 10, 2019 at 12:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .