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

>Only throw exceptions when something really bad has happened and the program must stop. For example:

> the program cannot connect to its database;

> the program cannot write output to disk because the disk is full;

> the program was not started with valid configuration.

I'd prefer Result over exceptions even in these cases. The only case where I think exceptions should be used is when the type system of the language is not powerful enough to prove the validity of some operation. For example in Rust:

  let v = vec![1, 2, 3];
  let n = v.pop().unwrap();
The `pop` method returns `Option`, but I as a programmer know for sure that the collection isn't empty, I just can't prove it to the compiler. So I use `unwrap` to get the value and panic in the case I'm actually wrong and made a stupid mistake.

Another example is division by zero. Using a `Result` as a return value of the division operator would be extremely inefficient and unergonomic. Panic/exception is the best way to handle this situation.

I believe dependent types can solve both of the problems above so we can get rid of exceptions completely. Unfortunately, there is no a single mainstream language that has them.



Another thing to call out is that you also need to be precise in what the error is. Division by zero is indeed a grave error, but only when your code is not logically thought out - there should never have been any codepaths that divide by zero in the first place. So the error that your should report is whatever cause the denominator to be zero, not division by zero. That's almost entirely useless, and misleading.




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

Search: