latvian
latvian

Reputation: 3215

How to avoid MissingPropertyException

If an object does not have a property and I am accessing the property, we get a MissingPropertyException. Can I do something similar to safe null (?.) to guard against missing properties so it doesn't throw an exception?

Upvotes: 19

Views: 26670

Answers (2)

Roman
Roman

Reputation: 857

You can also use try/catch

try
{   env.GERRIT_TOPIC=GERRIT_TOPIC
}
catch (e_val)
{   echo 'missing GERRIT_TOPIC'
}

Upvotes: 0

tim_yates
tim_yates

Reputation: 171114

One option would be:

def result = obj.hasProperty( 'b' ) ? obj.b : null

Which would return null if the object doesn't have the property...

Another would be to add propertyMissing to your class like so:

def propertyMissing( name ) {
  null
}

This means that any missing properties would just result in null.

Upvotes: 21

Related Questions