Created
March 7, 2012 15:08
-
-
Save lauripiispanen/1993705 to your computer and use it in GitHub Desktop.
Groovy TryCatch class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
] |
Also, please point me to where these "metaprogramming/monkey patching idioms" are in the above code?
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
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:
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.