Search code examples
javaerror-handlingassert

Is "assert false;" a good practice?


I am currently writing a function returning an object from a list according to a given criteria. It looks like this:

for (Object object : list) {
    if (condition(object)) {
        return object;
    }
}

This function should always return something from the list, and in the case no matching object was found, it was a bad call, a critical error, and the program should stop.

So, as I work with assertions enabled, I did the following just after the loop:

assert false; // Will always trigger in debug mode.
return null; // No matter anyway, an AssertionException has already been thrown.

But I wonder if I did well or not?
If not, what should I do instead? Throws an exception myself?

In any case, is there any kind of norm about this situation?


Solution

  • I would rather try to check the return value of the function when calling it.

    if (yourFunctionWithList(parameter) == null)
       //error handling, maybe throw new NPException or whatever. 
    else
       //some object was returned
    

    You may also write your own Exception class and handle it in any way you want.

    I personally do not think assert false is good practice.

    EDIT

    If it is about the AssertionException that will be thrown, then you could also use it like

    throw new AssertionError ("your error msg here");
    

    So you can handle it the same way