Java Assertion in getter method

426 Views Asked by At

Lets say we have this code:

Owner owner;
public Owner getOwner(int id)
{
    if (owner == null)
        owner = Owners.getOwner(id);
    assert owner != null;
    return owner;
}

What will happen if the Owners.getOwner(id) returns null? will the method die or it will still return null if an assertion is added before the return?

if getOwner(id) is asserted to null will still throw an NPE if getOwner(id).doSomething(); is called?

1

There are 1 best solutions below

0
On

Assertions can be turned on and off to run a program, and are off by default. If they are turned on and their condition is triggered the JVM throws an AssertionError. From your comments it seems that you don't have assertions enabled.

Because assertions can go away, you shouldn't base application logic on assertions: if you want to raise an error in a certain unexpected situation, throw an exception.