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.

import * as fs from 'fs';

function main() {
    // We'll use throw throughout this site to check for
    // unexpected errors. This is the only program on the
    // site designed to throw an error.
    throw new Error("a problem");

    // A common use of throw is to abort if a function
    // returns an error value that we don't know how to
    // (or want to) handle. Here's an example of
    // throwing if we get an unexpected error when creating a new file.
    try {
        fs.writeFileSync('/tmp/file', '');
    } catch (err) {
        throw err;
    }
}

main();

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.

$ ts-node panic.ts
Error: a problem
    at main (/path/to/panic.ts:7:11)
    at Object.<anonymous> (/path/to/panic.ts:20:1)
    ...

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.