14 ms·
Sometimes a nonlocal goto is exactly what you want. Consider some kind of validator/parser class/function, with a public entrypoint and a bunch of private subr
by zarzavat 4y ago
Sometimes a nonlocal goto is exactly what you want.
Consider some kind of validator/parser class/function, with a public entrypoint and a bunch of private subroutines that can fail when they hit invalid input:
public parse() {
try {
this.parseX();
this.parseY();
this.parseFoo();
...
} catch (e) {
throw new Error(...)
}
}
private parseY() {
this.y = this.input.y.map(a => {
if (bad data) throw new Error("corrupt data");
...
})
}
It's common in such situations to want to have one central point to collect errors in order to produce a single error type result.
It is possible to manually thread Results all the way through your logic, but that clutters the code with error handling. Rust's Try operator makes it easier but it's still awkward.
Exceptions allow us to concentrate on the two most important parts: where the exceptions are generated, and where they are handled (in this case, the root of the public interface).
I definitely agree that exceptions are not perfect. They have their own flaws, especially for public interfaces. But as control flow they are useful in many cases.