jMonkeyEngine / jmonkeyengine

A complete 3-D game development suite written in Java.
http://jmonkeyengine.org
BSD 3-Clause "New" or "Revised" License
3.84k stars 1.13k forks source link

SAXUtil throws inconsistent exceptions when it encounters wrong formats #1998

Open drhaozhong opened 1 year ago

drhaozhong commented 1 year ago

SAXUtil throws SAXException when formats are wrong. For example, a method is as follows:

public static int parseInt(String i, int def) throws SAXException{ if (i == null) return def; else{ try { return Integer.parseInt(i); } catch (NumberFormatException ex){ throw new SAXException("Expected an integer, got '"+i+"'"); } } }

The other classes throw IOException. For example, DOMInputCapsule.java has the following code:

public int readInt(String name, int defVal) throws IOException { String tmpString = currentElem.getAttribute(name); if (tmpString == null || tmpString.length() < 1) return defVal; try { return Integer.parseInt(tmpString); } catch (NumberFormatException nfe) { IOException io = new IOException(nfe.toString()); io.initCause(nfe); throw io; } catch (DOMException de) { IOException io = new IOException(de.toString()); io.initCause(de); throw io; } }

I assume that all wrong formats will throw IOException. As a result, my code fails to catch the exceptions thrown by SAXException.

Can jmonkeyengine fix the problem?

stephengold commented 1 year ago

According to the Javadoc, IOException is intended for failed or interrupted I/O operations. It is often used for wrong formats, but that's not the only way to do things.

The "org.xml.sax" package assumes all parse errors will produce a SAXException, so if you use that package you shouldn't assume that all wrong formats will throw IOException.

pspeed42 commented 1 year ago

re: "It is often used for wrong formats, but that's not the only way to do things."

...that's because on some level it's a value judgment between "is this bad because the data is bad" and "is this bad because the stream is bad". The thing interpreting the stream can't always be sure. (It might even be provable that it can never be sure.)