0Pricing
TypeScript Academy · Lesson

The Problem with Throwing Errors

Why exceptions hide failure from the type system.

Exceptions Are Invisible

When a function throws, its signature does not say so. The type system cannot see which functions may fail, so callers have no compiler nudge to handle errors.

A Throwing Function

This function looks like it always returns a number, but it can throw. The return type number hides the failure case completely.

function parsePort(s: string): number {
  const n = Number(s);
  if (Number.isNaN(n)) throw new Error("bad port");
  return n;
}
console.log(parsePort("8080")); // 8080

All lessons in this course

  1. The Problem with Throwing Errors
  2. Modeling Result Types
  3. Option and Maybe Types
  4. Railway-Oriented Programming
← Back to TypeScript Academy