AnyCompiler

Exception Handling (try/catch)

try/catch works the same as JavaScript — code that might fail goes in try, and catch runs instead of crashing if something throws.

try {
  const result = JSON.parse("not valid json");
} catch (error) {
  console.log("Could not parse JSON!");
}
Output
Could not parse JSON!

Why the caught error is unknown

JavaScript lets you throw literally anything — a string, a number, an actual Error object. Because TypeScript can't know in advance what a given throw will produce, it types the caught value as unknown rather than any, which forces you to check its type before using it.

try {
  JSON.parse("not valid json");
} catch (error) {
  if (error instanceof Error) {
    console.log(`Error: ${error.message}`);
  }
}
Output
Error: Unexpected token o in JSON at position 1

error instanceof Error narrows the type from unknown down to Error, which is what actually makes error.message accessible — accessing .message on an unknown value directly would be a compile error.

Next: type narrowing — the general pattern behind that instanceof check, and the other ways TypeScript narrows types.

Practice exercise

Write a function safeDivide(a: number, b: number): number that throws an error if b is 0, otherwise returns a / b. Call it inside a try/catch with b = 0, and print "Cannot divide by zero" in the catch block.