Skip to content

Instantly share code, notes, and snippets.

@lauripiispanen
Created March 7, 2012 15:08
Show Gist options
  • Save lauripiispanen/1993705 to your computer and use it in GitHub Desktop.
Save lauripiispanen/1993705 to your computer and use it in GitHub Desktop.
Groovy TryCatch class
public static def _try(attempt) {
return new TryCatch(attempt: attempt)
}
public static class TryCatch {
def attempt
public def _catch(clos) {
try {
return attempt();
} catch (Exception e) {
return clos(e);
}
}
public def getCatch() {
return _catch { null }
}
}
/* USAGE */
def caption = _try { very.long.gpath.find {it.name == "expression"}?.with?.array.operation[0] }._catch { "" }
// null default
[
width: _try { attrs.width as int }.catch,
height: _try { attrs.height as int }.catch,
]
@lauripiispanen
Copy link
Author

While I agree with several of your points, and note that this was rather an exercise in bending Groovy towards more "core language-like" constructs, this point I do not understand:

What really is bad though is that the try..catch class doesn't really convey the meaning of the calling structure.

It is not the class that does not convey the structure, but rather how the empty catch is used in the calling code. An try {} without catch or finally is disallowed in Java, so natural way to write that would be __try { something() }.catch { null }.

Also, the Java 7 solutions still don't address what this thought experiment does: you still can't return a value from try-catch.

@lauripiispanen
Copy link
Author

Also, please point me to where these "metaprogramming/monkey patching idioms" are in the above code?

@lauripiispanen
Copy link
Author

Also now that you have a try..catch, what about try..catch..finally?

Did cross my mind. Working on it... ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment