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

Java and C# have the `finally` block which is essentially the `goto fail`. Typically it is used like:

  try {
    doSomething();
  }
  catch (Exception e) {
    handleException();
  }
  finally {
    cleanUpResources();
  }
When the code exits the try block, you are guaranteed that it will run the finally block, possibly entering the catch block first if an exception was thrown. Since the most common use of `goto fail` pattern is freeing memory, the `finally` block isn't actually used a lot in Java/C# code in practice.


Thank you. Since the example was nothing to do with exceptions, and we don't want to abuse exceptions by using them when they are not needed, I will rewrite your example to cover the GP case:

   Foo foo = acquireFoo();
   try {
       if (!isValid(foo)) {
          return FAIL;
       }
       moreWork(foo);
       return SUCCESS;
   } finally {
       releaseFoo(foo);
   }
Python could also use the same approach. Though it also has context managers / the with-statement for this specific application.




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

Search: