I am working on exception handling in one of my static methods. I've discovered the MissingMethodException (through trial and error) but when I write code to catch it, Grails 2.3.11 is ignoring the catch block. Not even the default Exception is being used. Why isn't the exception being caught?
package utility
import java.text.SimpleDateFormat
class DateUtility {
static String getGrailsDefaultDate(String datetm) {
def format = new SimpleDateFormat("YYYYMMddHHmmss")
try{
def date = format.parse(datetm)
date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(date)
datetm = date.toString()
}
catch(IllegalArgumentException iae){
datetm = "An error occured retrieving the date"
}
catch(NullPointerException npe){
datetm = "A date was not provided"
}
catch(java.text.ParseException pe){
datetm = "Unparseable date"
}
catch(groovy.lang.MissingMethodException mme){
datetm = "A missing method occured"
}
catch(Exception e){
datetm = "default exception"
}
return datetm
}
}
And here is the call which should throw the missing method exception:
DateUtility.getGrailsDefaultDate(1)
Why isn't the exception being caught?
Your catch
block is only going to catch exceptions that are thrown from your try
block. There are no expressions in your try
block which are going to throw a MissingMethodException
, so your catch
block that catches MissingMethodException
isn't going to be invoked. This all looks to be working as designed.
If you put your DateUtility.getGrailsDefaultDate(1)
inside of a try
block that has a catch
block associated with it which catches MissingMethodException
, then that catch
block would be invoked.
Try this...
class DateUtility {
static String getGrailsDefaultDate(String datetm) {
def format = new SimpleDateFormat("YYYYMMddHHmmss")
try{
def date = format.parse(datetm)
date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(date)
datetm = date.toString()
}
catch(IllegalArgumentException iae){
datetm = "An error occured retrieving the date"
}
catch(NullPointerException npe){
datetm = "A date was not provided"
}
catch(java.text.ParseException pe){
datetm = "Unparseable date"
}
catch(groovy.lang.MissingMethodException mme){
datetm = "A missing method occured"
}
catch(Exception e){
datetm = "default exception"
}
return datetm
}
static void main(args) {
try {
DateUtility.getGrailsDefaultDate(1)
} catch (MissingMethodException mme) {
println 'I Caught The Exception!'
}
}
}