مرکزی مواد پر جائیں
eLearner.app
ماڈیول 5 · سبق 4 از 4کورس میں 20/32~12 min
ماڈیول اسباق (4/4)

کوشش / پکڑنا / پھینکنا

An error in JavaScript is a value (usually an Error object) that interrupts the normal flow and bubbles up the call stack until someone catches it. The construct to handle this case is try / catch.

Throwing an error: throw

JS
function dividi(a, b) {
  if (b === 0) {
    throw new Error('Divisione per zero');
  }
  return a / b;
}

throw immediately interrupts the current function.

Catching: try / catch

JS
try {
  const r = dividi(10, 0);
  console.log('ok', r);
} catch (err) {
  console.log('errore:', err.message); // 'errore: Divisione per zero'
}

// Il programma continua qui, anche se c'è stato un errore.

Everything inside try is executed; if an error is thrown (via throw or by any operation that fails), control jumps to the catch block. The variable after catch (...) receives the error.

finally (optional)

Code that always runs, error or not. Useful to close resources:

JS
try {
  // ... operazione rischiosa
} catch (err) {
  // ... log
} finally {
  // ... pulizia (sempre eseguita)
}

When to use it (and when not)

  • Yes: I/O operations (JSON.parse on untrusted input, fetch, disk access), conversions that can fail.
  • Maybe not: for the normal flow. If you know an input may be invalid, it is better to check it with an if than to throw and catch.
JS
// Tipico: parsing JSON difensivo
function parseJsonSafe(text) {
  try {
    return { ok: true, value: JSON.parse(text) };
  } catch (err) {
    return { ok: false, error: err.message };
  }
}

parseJsonSafe('{"a":1}'); // { ok: true, value: {a:1} }
parseJsonSafe('non json'); // { ok: false, error: '...' }

Try it

ورزش#js.m5.l4.e1
کوششیں: 0لوڈ ہو رہا ہے…

Define `safeDivide(a, b)`: if b is 0 throw an Error with message 'Divisione per zero', otherwise return a/b.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

if (b === 0) throw new Error('...'); then return a / b.

3 کوششوں کے بعد حل دستیاب ہے۔

Review exercise

ورزش#js.m5.l4.e2
کوششیں: 0لوڈ ہو رہا ہے…

Define `parseJsonSafe(text)`: if text is valid JSON return { ok: true, value: <object> }, otherwise { ok: false }. Use try/catch on JSON.parse.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Wrap JSON.parse in try; in the catch return { ok: false }.

3 کوششوں کے بعد حل دستیاب ہے۔