Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.

try/catch keeps failures visible instead of silent

PHP and JavaScript share the same shape: try, catch, finally. The main difference is JavaScript has no typed catch — you inspect the error inside the block.

PHP habit

<?php
try {
    $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo 'Invalid JSON: ' . $e->getMessage();
} finally {
    fclose($handle);
}

throw new InvalidArgumentException('Email is required');

JavaScript equivalent

try {
  const data = JSON.parse(raw);
} catch (error) {
  console.error('Invalid JSON:', error.message);
} finally {
  closeHandle();
}

throw new Error('Email is required');
PHP JavaScript Notes
catch (JsonException $e) catch (error) then instanceof One catch clause
$e->getMessage() error.message On Error objects
throw new Exception('msg') throw new Error('msg') Prefer Error for stack traces
finally always runs finally always runs Same

Narrowing the error type inside catch

try {
  risky();
} catch (error) {
  if (error instanceof TypeError) {
    console.error('Type problem:', error.message);
  } else if (error instanceof SyntaxError) {
    console.error('Syntax problem:', error.message);
  } else {
    throw error;
  }
}

Re-throw what you cannot handle — same discipline as PHP.

Throw Error, not bare strings

throw new Error('User not found');
// avoid: throw 'User not found';

Bare strings lose stack traces and are harder to debug in production.

Validation pattern you will reuse

function parseAge(input) {
  const age = Number(input);
  if (Number.isNaN(age)) {
    throw new Error('Age must be a number');
  }
  if (age < 0 || age > 150) {
    throw new Error('Age out of range');
  }
  return age;
}

Same flow as throwing InvalidArgumentException in PHP services.

Try it

Use the amber Try it panel below. Click Run.

function divide(a, b) {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}

for (const pair of [[10, 2], [10, 0]]) {
  try {
    console.log(`${pair[0]} / ${pair[1]} =`, divide(...pair));
  } catch (error) {
    console.error('Caught:', error.message);
  } finally {
    console.log('Attempt finished');
  }
}

First division succeeds; second logs a caught error. finally runs both times.

From PHP to JavaScript — JavaScript Syntax Foundations for PHP Devs