This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have below code in a JSP as a method. When the date is null, the method throws StringIndexOutOfBoundsException and stops executing. Isn't this the whole point of putting the try/catch block in this code? Why does the code stop executing (stop loading the page)?
When "date" is null, you'd see a NullPointerException, not an index exception; you'd see the latter if "date" were the empty string "".
Regardless of which was thrown, this method should complete. What makes you think that it's this method that's raising the error? Perhaps it's another method that tries to use the empty String that this one returns.
I see the error in Tomcat log file, also when I comment out the substring statements, I don't get the exception (so I am pretty sure that this is the statement causing the exception and page stop loading).
Originally posted by Ali Ekber: I see the error in Tomcat log file, also when I comment out the substring statements, I don't get the exception (so I am pretty sure that this is the statement causing the exception and page stop loading).
Then the date cannot possibly be null; it's a range problem. Couple side notes: you should rarely if ever catch Exception and it's not good form to place code on a JSP nowadays.
Better you can check at the first itself whether the date is null like giving date.equals("null") if so dont do anything.. or display what u would like to do.. in the else case .. you parse the string to your own format..
Ramesh Shanmugam - SCJP 1.5
author and iconoclast
Originally posted by Ramesh Shanmugam: date.equals("null")
First, if date is null, this will give a NullPointerException, because you're calling a method on it, so this can never succeed! Second, the String "null" is not at all the same as the literal constant null!
To check if the variable date is null, you'd write