19 ms·
This is a great philosophy, but I'd hesitate to say "all" variables; sometimes it just doesn't work out. ex, in class definition: final int foo; In constru
by twir 17y ago
This is a great philosophy, but I'd hesitate to say "all" variables; sometimes it just doesn't work out.
ex, in class definition:
final int foo;
In constructor:
try {
foo = 1;
} catch ( Exception e ) {
foo = 2;
}
- lsb 17y agoIf your try{} catch{} blocks were expressions, not statements, you could write foo = try { 1 } catch(Exception e) { 2 } much like the foo = bool ? 1 : 2 ternary if statement, versus the if() {} else {} clauses.
- twir 17y agoWow, never knew one could do that.
- nradov 17y agoYou can't do that. It would require a language change, to make try/catch blocks expressions.
- twir 17y agoHeh, I didn't think so. ;)
- eldenbishop 17y agoYou can sort of do this in Groovy. def val = {try { 1 } catch(ex) { 2 }}.call() assert(1 == val)
- nradov 17y agoIn cases like that I usually exact the try/catch block into a separate private method which returns an int. Then the constructor can just call that method and use the return value to set foo.