Panic in TypeScript
A throw
statement in TypeScript typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully.
Running this program will cause it to throw an error, print an error message and stack trace, and exit with a non-zero status.
When the first throw
in main
executes, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment the first throw
out.
Note that unlike some languages which use exceptions for handling of many errors, in TypeScript it is idiomatic to use error-indicating return values (like Result
types or nullable values) wherever possible, and use throw
for truly exceptional circumstances.
In TypeScript, we don’t have the concept of “goroutines” as in Go. Instead, for asynchronous operations and concurrency, we typically use Promises, async/await, or callbacks. The error handling shown here is synchronous, but similar principles apply to asynchronous error handling using try/catch
with async/await
or .catch()
with Promises.