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

By "not Pythonic" I've meant that this issue is not unique to Python. It's not a problem created by some Python dogma. It's a fundamental issue affecting all languages, even those that don't have a catchy slogan for it. In Rust and C you also need to "try first, ask forgiveness later".

For example, you can never be sure whether you can open a file until you actually open the file and it doesn't fail. If you tried to check if the file exists and has correct permissions before opening it, you'd have possibility of a race condition. So the correct approach is to try the operation head first and handle the failure, instead of trying to somehow gracefully avoid creating an "exceptional" situation.



My bad! Text is funny sometimes, isn't it?

I agree with your basic argument here and you've convinced me to some extent. I wanted to dredge up some examples to highlight inherent flaws in Python's error handling ergonomics, but I was pleasantly surprised by new language features that made the experience much more enjoyable (the with ... as keywords, in particular).

I will say this though: try/except still sucks, in my opinion. I much prefer languages whose standard libraries utilize monads/callbacks for error handling, because it offloads much of the work/documentation onto the type system, as opposed to languages/frameworks which prefer error handling as part of a try/catch statement.

Monad Example (Scala documentation - Try monad [1] ):

  import scala.util.{Try, Success, Failure}

  def divide: Try[Int] = {
    val dividend = Try(Console.readLine("Enter an Int that you'd like to divide:\n").toInt)
    val divisor = Try(Console.readLine("Enter an Int that you'd like to divide by:\n").toInt)
    val problem = dividend.flatMap(x => divisor.map(y => x/y))
    problem match {
      case Success(v) =>
        println("Result of " + dividend.get + "/"+ divisor.get +" is: " + v)
        Success(v)
      case Failure(e) =>
        println("You must've divided by zero or entered something that's not an Int. Try again!")
        println("Info from the exception: " + e.getMessage)
        divide
    }
  }
Callback Example (NodeJS documentation - fs.readFile function [2] ):

  fs.readFile('/etc/passwd', (err, data) => {
    if (err) throw err;
    console.log(data);
  });
[1]: https://www.scala-lang.org/api/2.9.3/scala/util/Try.html [2]: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_c...




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

Search: