3 ms·
The first example code is rather off-putting, because it has multiple errors. The code would not throw an exception, because it produces compiler errors so you’
by chrismorgan 6y ago
The first example code is rather off-putting, because it has multiple errors. The code would not throw an exception, because it produces compiler errors so you’ll never run it. (OK, so it still generates JavaScript that you could run, but I’m assuming you’re using TypeScript properly and won’t do so.)
• `return number + 1;` should be `return someNumber + 1;`. If you ignore errors and run the JavaScript, this means that it’ll throw a ReferenceError on this line.
• `bar(someNumber) + bar;` is adding a number (well, it should be a number, but you’ve omitted the return types, so the previous error will mean it infers `any` instead of `number`) to a function. This is a type error.
• `baz()` is called with zero arguments instead of the one it requires.
> When baz is called it will throw an uncaught exception. By reading the code you know that foo throws an Error. Debugging this snippet is a piece of cake, right?
As mentioned, this code doesn’t compile, but if you ignore that and run it anyway, then the uncaught exception is a ReferenceError, not the error you see on a throw line. I… don’t think this is what was intended. This also demonstrates what I consider a bit of a weakness of the exception system in such languages: various programming errors that a compiler should catch come through as runtime errors instead.
(I’d generally prefer to use exceptions to indicate exclusively programmer errors, and basically never use a try/catch block, but too much is designed around treating exceptions as normal parts of control flow to be able to do this in most cases. I like the Result/panic split in Rust, where panic always means programmer error, and Result is for probably-exceptional cases, but where they’re still generally expected and part of the design rather than programmer error.)
If you fixed only the first error, you’d get a value like "NaNfunction bar(someNumber) {\n return foo(someNumber) + 1;\n}" out of the baz() call. Fun times.
- robocat 6y agoAuthor has now fixed the example: https://news.ycombinator.com/item?id=24454455 https://news.ycombinator.com/item?id=24454455
- valand 6y agoAuthor here. Caught red-handed not running it on playground. Thanks for the correction. > I’d generally prefer to use exceptions to indicate exclusively programmer errors The idea that panic/exception means programmer errors worth to be noted. It think they should be intended for errors that is intended to be unrecoverable. Still, catching errors on runtime is not fun