Posts Tagged ‘exception’

A Simple Mistake of Using Java Exception

2011/09/01

Recently I ran into the following code in a legacy system:

try {
...
} except (Exception e) {
System.out.println(e.getStackElement());
}

While it may look innocent, it’s actually dangerous. In case of an exception, the system prints the String representation of e.getStackElement(), which actually is of type StackElement[]. Since it is an array, its String representation is only the address of the array, instead of the content of the array. Since the output is a one-liner, it does not catch one’s eye in the log, and it may take some time (and really took mine) for the debugger to find the exception.

I have no idea why the original programmer come up with the idea of using getStackElement(). Maybe he thought println(e.getStackElement()) were the same as e.printStackElement().

How to Use Exceptions: An Example

2011/08/09

Today I had to debug a legacy system, including a feature, let me call it xy. In the property file, there were two properties concerning this feature: “xy.enabled” and “xy.url”. “xy.enabled” is used to indicate whether the feature should actually be activated, and if it is true, the system needs to read some data from a URL stored in “xy.url”.

The defect of this system was that even “xy.enabled” is changed to “true”, the feature xy was still not activated in the system.

It was not very easy to find the problem, but after a while of debugging, I finally got it: the original programmer made a mistake while coding, and reading the property “xy.enabled” is done by a method Util.getBooleanProperty(“xy.url”). Obviously, “xy.url” is wrong. I replaced it by “xy.enabled”, and it worked fine.

But why does the original code, with Util.getBooleanProperty(“xy.url”), not throw an exception? Obviously getBooleanProperty is supposed to read a string representing a boolean value, obviously xy.url does not a boolean value!

Yes, that’s true. The method getBooleanProperty reads like this:


public static getBooleanProperty(String property) {
return getProperty(property).equalsIngoreCase("true");
}

where getProperty(String p) returns the String value of property p stored in the property file.

getBolleanProperty really does not throw any exception if the value is not a boolean value at all!

If the original programmer had designed any syntax check, or simpley used Boolean.valueOf, which throws an exception if the parameter is malformed, debugging this problem would have been much easier. This is where exceptions are supposed to help.