Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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;
  }


If 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.


Wow, never knew one could do that.


You can't do that. It would require a language change, to make try/catch blocks expressions.


You can sort of do this in Groovy.

  def val = {try { 1 } catch(ex) { 2 }}.call()
  assert(1 == val)


Heh, I didn't think so. ;)


In 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.




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: