Try { ... } catch

Using the XmlReader plugin, I’d like to read a certain element’s attribute using this code:

_ID = _columnNode.getAttributeValue("id");

if (_ID == null) {
  // error handling
} else {
  // do something
}

Now, when this attribute “id” doesn’t exist, a nullpointer exception gets triggered at the first line.

Because exceptions aren’t always bad things, I tried using a try … catch to prevent the exception:

try {
  _ID = _columnNode.getAttributeValue("id");
} catch(theErr)	{
  // error handling
}

Despite the try … catch, the nullpointer exception still gets triggered!

Using the reference guide, I found out that I should loop trough the attributes using the xmlNode.getAttributeNames() function, but I was wondering why the try … catch block doesn’t catch the nullpointer exception. Any ideas or suggestions?

You could first call getAttributeNames(). That should give you all the attributes. Then you can check, whether your attribute is present.

Or an even better option: have a look at the XML-Plugin! :lol:

Thanks for the quick response patrick, but I already figured that part out. I wonder why the try … catch block doesn’t seem to work in this case. Maybe I’m using it in a wrong way?

Do you observer this behavior in developer with the debugger on? Or also in the client? With debugger and exception break enabled, you will end in the catch block…

Anyway: the plugin shouldn’t throw a NullPointerException at that point.

It occurs in Developer with both debugger on or off. Client not yet tested, but in my opinion it should just work :wink:.

try { 
  _ID = _columnNode.getAttributeValue("id"); 
} catch(theErr)   { 
  // error handling 
}

Is the error really thrown in Servoy or do you only find it in your stacktrace.
Don’t know about this plugin but it is possible to design a plugin in a way that it doesn’t throw the error in Servoy.
If that is the case your try/catch block will not work.

BTW I agree that, once you get the hang of it, a try/catch/finally block can make an error work FOR you instead of AGAINST you…