Question

I have a project in which certain data has invariants which are not enforceable using language constructs, but I've intended to write my code such that they are maintained. If they are for some reason broken, it means that my code is buggy. I have some sanity check code which can discover if these invariants have been broken, but I'm not sure what is the canonical Java approach to responding to such a condition - is there some standard exception that I should throw? Use an assert?

Note that this is an issue of a value being set incorrectly at some point. The error itself does not occur at the time of the sanity check, but rather it occurred in the past, and the sanity check is just now discovering it (ie, it's not bad that the sanity check itself is running, it's just bad that the check failed).

Thanks!

Was it helpful?

Solution

Throw an IllegalStateException. It is meant specifically for purposes like this.

OTHER TIPS

Deciding how your application would react to a broken invariant would be a sensible first step

In case a broken invariant is unrecoverable and basically means a bug a code, i second an answer about IllegalStateException.html (you may want to add some useful context for debug purposes ,e.g. variables in broken invariant) - such unchecked exception would stop a running thread

In case you can recover from broken invariant (by replacing some arguments with sensible default, giving it a second try) - you may want to throw a checked exception and catch it on one of upper layers and execute plan B

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top