Thuta Learning
JavaScript
IntermediateProgrammingအခြေခံ

Try...Catch

JavaScriptသင်ခန်းစာ 2025 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • try, catch, finally block တစ်ခုစီ ဘယ်အချိန် run လဲ အစဉ်လိုက် ခန့်မှန်းနိုင်ဖို့
  • throw new Error(...) နဲ့ မမှန်တဲ့ input ကို error အဖြစ် ပစ်နိုင်ဖို့
  • try...catch က ဘာကို ဖမ်းနိုင်ပြီး ဘာကို မဖမ်းနိုင်လဲ (setTimeout, await မလုပ်တဲ့ Promise) ခွဲခြားနိုင်ဖို့
  • Fallback value နဲ့ recover လုပ်တာနဲ့ context ထည့်ပြီး rethrow လုပ်တာကြား ရွေးနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

ကြိုးတန်းပေါ်မှာ လမ်းလျှောက်တဲ့ ပွဲထုတ်သူ အောက်မှာ ပိုက်ကွန် ခင်းထားတာကို မြင်ဖူးမှာပါ။ ပြုတ်မကျရင် ပိုက်ကွန်ကို ဘယ်တော့မှ မသုံးရပေမယ့် ပြုတ်ကျရင်တော့ ပိုက်ကွန်က ဖမ်းထားပြီး ပွဲက ဆက်သွားနိုင်ပါတယ်။ ပွဲပြီးတော့ ပြုတ်ကျကျ မကျကျ ကြိုးတန်းကို ပြန်သိမ်းရပါတယ်။

try block က ကြိုးတန်းပေါ်က လမ်းလျှောက်တာ၊ catch block က ပိုက်ကွန်၊ finally block က ပွဲပြီးတိုင်း လုပ်ရမယ့် သိမ်းဆည်းမှုပါ။ try ထဲမှာ error တက်ရင် ကျန်တဲ့ code ကို ကျော်ပြီး catch ဆီ တန်းရောက်သွားပြီး program က crash မဖြစ်ဘဲ ဆက် run ပါတယ်။

Problem → Why → Solution

ပြဿနာ: catch အလွတ်က error ကို ဖျောက်ပြီး ဝေးတဲ့နေရာမှာ crash စေတယ်

အောက်က loadSettings() က JSON parse မအောင်မြင်ရင် ဘာမှ မလုပ်ဘဲ error ကို မျိုချထားပါတယ်။ Settings file ထဲမှာ trailing comma တစ်ခု ပါသွားတဲ့နေ့မှာ function က undefined ကို ပြန်ပေးပြီး program က ဆက်သွားပါတယ်။ Crash က settings.theme ကို ဖတ်တဲ့ နောက်တစ်နေရာမှာမှ ဖြစ်ပြီး error message က JSON နဲ့ လုံးဝ မဆိုင်သလို ဖြစ်နေလို့ debugging လုပ်ရတာ ခက်ပါတယ်။

settings.js
function loadSettings(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    // ignore it
  }
}

const settings = loadSettings('{"theme": "dark",}'); // trailing comma
console.log(settings.theme);
// TypeError: Cannot read properties of undefined (reading 'theme')

ဘာကြောင့် ဒီလို ဖြစ်တာလဲ

catch block က error ကို ဖမ်းပြီးတာနဲ့ program က "ပြဿနာ ပြေလည်သွားပြီ" လို့ ယူဆပါတယ်။ ဒါပေမယ့် ဒီ catch က ဘာမှ မပြင်ဘဲ မမှန်တဲ့ state (undefined) နဲ့ ဆက်သွားခွင့်ပေးလိုက်တာပါ။ catch တိုင်းမှာ fallback value ပေးပြီး တကယ် recover လုပ်မလား၊ ဒါမှမဟုတ် context ထည့်ပြီး rethrow လုပ်မလား ဆုံးဖြတ်ရပါမယ်။

Core concept: try, catch, finally ရဲ့ လမ်းကြောင်း

try block ထဲက code ကို ပုံမှန်အတိုင်း run ပါတယ်။ Statement တစ်ခုက error ပစ်လိုက်တာနဲ့ try ထဲက ကျန်တဲ့ စာကြောင်းတွေကို ကျော်ပြီး catch (error) block ဆီ ခုန်သွားပါတယ်။ error variable ထဲမှာ name, message, stack ပါတဲ့ Error object ရှိပါတယ်။ Error မတက်ရင် catch ကို လုံးဝ ကျော်သွားပါတယ်။ Error object ကို မလိုရင် catch { ... } လို့ parameter မပါဘဲလည်း ရေးလို့ရပါတယ်။

finally block ကတော့ try အောင်မြင်အောင်မြင်၊ catch run run၊ try ထဲမှာ return ရှိရှိ အမြဲ run ပါတယ်။ File ပိတ်တာ၊ loading spinner ဖျောက်တာ၊ lock ဖြုတ်တာလို သိမ်းဆည်းမှု အလုပ်တွေအတွက် သုံးပါတယ်။ try ထဲက return value ကို အရင်တွက်ထားပြီး finally run ပြီးမှ caller ဆီ ပြန်ပို့ပါတယ်။ ဒါကြောင့် example ထဲမှာ "Division operation completed" က "Result: 5" ရဲ့ အရင် print ထွက်တာပါ။

throw statement နဲ့ error ကို ကိုယ်တိုင် ပစ်လို့ရပါတယ် — throw new Error("Cannot divide by zero")။ JavaScript မှာ 10 / 0 က error မဟုတ်ဘဲ Infinity ဖြစ်လို့ business rule အရ မမှန်တာကို ကိုယ်တိုင် စစ်ပြီး throw လုပ်ရပါတယ်။ try...catch က synchronous error တွေနဲ့ async function ထဲမှာ await လုပ်ထားတဲ့ Promise ရဲ့ rejection တွေကို ဖမ်းပါတယ်။ setTimeout callback ထဲက error၊ await မလုပ်ထားတဲ့ Promise rejection နဲ့ code ကို parse လုပ်တုန်း ဖြစ်တဲ့ syntax error တွေကိုတော့ မဖမ်းနိုင်ပါဘူး — try block ကနေ ထွက်သွားပြီးမှ ဖြစ်တာ ဒါမှမဟုတ် run မစခင် ဖြစ်တာမို့ပါ။

catch ထဲရောက်ရင် မေးခွန်းတစ်ခုကို ဖြေရပါတယ် — "ဒီနေရာမှာ ဒီ error ကို တကယ် ပြေလည်အောင် လုပ်နိုင်လား"။ Cache ထဲက data ဟောင်းကို ပြတာ၊ default setting သုံးတာလို အဓိပ္ပာယ်ရှိတဲ့ fallback ရှိရင် recover လုပ်ပါ။ မရှိရင် context ထည့်ပြီး rethrow လုပ်ကာ ပိုအပေါ်က code (ဥပမာ page ရဲ့ error handler) ကို ဆုံးဖြတ်ခွင့် ပေးပါ။ Error ကို အောက်ဆုံးအဆင့်မှာ အတင်း ဖမ်းထားတာထက် ကိုင်တွယ်နိုင်တဲ့ အဆင့်ရောက်မှ ဖမ်းတာ ပိုကောင်းပါတယ်။

မှတ်ထားရမယ့် ပုံစံ
  1. try ထဲက code ကို အစဉ်လိုက် run
  2. throw ဖြစ်တာနဲ့ catch ဆီ ခုန်
  3. catch: recover ဒါမှမဟုတ် rethrow
  4. finally က ဘယ်လိုပဲ ဖြစ်ဖြစ် run

catch ဆိုတာ "error ကို ဖျောက်ဖို့" မဟုတ်ဘဲ "error နဲ့ ဘာလုပ်မလဲ ဆုံးဖြတ်ဖို့" နေရာပါ။

အထွေထွေ ပုံစံ

javascript
try {
  riskyOperation();              // may throw
} catch (error) {
  if (canRecover(error)) useFallback();
  else throw new Error("Context about the task", { cause: error });
} finally {
  cleanUp();                     // always runs
}

if (badInput) throw new Error("Describe what is wrong");

catch ထဲမှာ recover လုပ်လို့ရတဲ့ error ဆိုရင် fallback သုံးပြီး မရရင် context ပါတဲ့ error အသစ်ကို { cause } နဲ့ မူရင်း error ချိတ်ပြီး ပြန်ပစ်ပါတယ်။ finally က cleanup အတွက်ပါ။

Example: ဖမ်းခြင်း၊ ပစ်ခြင်း နဲ့ finally

Run မလုပ်ခင် output ကို ခန့်မှန်းပြီးမှ အချက်သုံးချက်ကို စစ်ကြည့်ပါ။ JavaScript မှာ သုညနဲ့ စားတာက error မဟုတ်လို့ ReferenceError ကို မဖမ်းခင် Infinity ကို အရင် print ထုတ်ပါတယ်။ finally က return value ဟာ function ကို ခေါ်တဲ့ console.log ဆီ မရောက်ခင် run လို့ "Division operation completed" က "Result: 5" ရဲ့ အရင်မှာ ပေါ်ပါတယ်။ divideNumbers(10, 0) ကတော့ null ကို return ပြန်ပြီး "Result: null" လို့ print ထွက်ပါတယ်။

try-catch.js
// 1. Not every bad operation throws
try {
  const result = 10 / 0;
  console.log(result); // Infinity: not an error in JavaScript

  const x = y + 5; // ReferenceError: y is not defined
  console.log(x);  // never runs
} catch (error) {
  console.log(`Error caught: ${error.message}`);
}

// 2. throw, catch and finally together
function divideNumbers(a, b) {
  try {
    if (b === 0) {
      throw new Error("Cannot divide by zero");
    }
    return a / b;
  } catch (error) {
    console.log(`Error: ${error.message}`);
    return null;
  } finally {
    console.log("Division operation completed");
  }
}

console.log(`Result: ${divideNumbers(10, 2)}`);
console.log(`Result: ${divideNumbers(10, 0)}`);

// 3. Reacting to a specific kind of error
try {
  JSON.parse("invalid json");
} catch (error) {
  if (error instanceof SyntaxError) {
    console.log("Invalid JSON format");
  }
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Line 3const result = 10 / 0;

    သုညနဲ့ စားတာက JavaScript မှာ error မဟုတ်ဘဲ Infinity ရလို့ catch ကို မရောက်ပါဘူး။ ဒါကြောင့် ဒီလို rule တွေကို ကိုယ်တိုင် စစ်ပြီး throw လုပ်ရပါတယ်။

  2. Line 6const x = y + 5; // ReferenceError: y is not defined

    ကြေညာမထားတဲ့ y ကို ဖတ်လို့ ReferenceError တက်ပါတယ်။ နောက်က console.log(x) ကို ကျော်ပြီး catch ဆီ တန်းရောက်သွားလို့ "Error caught: y is not defined" ရပါတယ်။

  3. Line 16throw new Error("Cannot divide by zero");

    b က 0 ဖြစ်ရင် Error object ကို ကိုယ်တိုင် ပစ်ပါတယ်။ return a / b ကို ကျော်ပြီး catch က message ကို print ထုတ်ကာ null ကို return ပြန်ပါတယ်။

  4. Lines 22-24} finally {

    finally က call နှစ်ခုလုံးမှာ run ပါတယ်။ return value ကို caller ဆီ မပို့ခင် run လို့ "Division operation completed" က "Result: ..." ရဲ့ အရင်မှာ ထွက်ပါတယ်။

  5. Line 34if (error instanceof SyntaxError) {

    Error အမျိုးအစားကို instanceof နဲ့ စစ်ပြီး ကိုယ်ကိုင်တွယ်နိုင်တဲ့ အမျိုးအစားကိုပဲ တုံ့ပြန်ပါတယ်။ Message စာသားကို စစ်တာထက် ဒီနည်းက ပိုခိုင်မာပါတယ်။

You should see
Infinity
Error caught: y is not defined
Division operation completed
Result: 5
Error: Cannot divide by zero
Division operation completed
Result: null
Invalid JSON format

async/await နဲ့ error cause

async function ထဲမှာ await လုပ်ထားတဲ့ Promise reject ဖြစ်ရင် synchronous throw လိုပဲ catch ဆီ ရောက်ပါတယ်။ Error ကို ပြန်ပစ်တဲ့အခါ new Error(message, { cause: error }) နဲ့ မူရင်း error ကို ချိတ်ထားရင် "ဘာလုပ်နေတုန်း" (profile page load) နဲ့ "ဘာကြောင့်" (user မတွေ့) နှစ်ခုလုံး log ထဲမှာ ကျန်ပါတယ်။

async-cause.js
async function fetchUser(id) {
  throw new Error(`User ${id} not found`);
}

async function loadProfile() {
  try {
    await fetchUser(7);
  } catch (error) {
    const wrapped = new Error("Could not load profile page", { cause: error });
    console.log(wrapped.message);              // Could not load profile page
    console.log(`Caused by: ${wrapped.cause.message}`); // Caused by: User 7 not found
  }
}

loadProfile();

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Web app တွေမှာ try...catch ကို system ရဲ့ နယ်နိမိတ် (boundary) တွေမှာ အများဆုံး တွေ့ရပါတယ် — user ထည့်တဲ့ JSON ကို parse လုပ်တာ၊ API ကို fetch လုပ်တာ၊ file ဖတ်တာ။ ဥပမာ config file loader က malformed JSON ဆိုရင် "file ကို ပြင်ပါ" လို့ ပြောပြီး field ပျောက်နေရင် "port field လိုတယ်" လို့ ကွဲကွဲပြားပြား ပြောပေးရပါမယ်။ Caller ကလည်း { ok, value, error } လို တသမတ်တည်း ပုံစံ ရလို့ if တစ်ခုတည်းနဲ့ စစ်နိုင်ပါတယ်။

finally ကိုတော့ UI မှာ loading state ပြန်ပိတ်ဖို့ အမြဲသုံးပါတယ် — setLoading(true) ပြီး try ထဲမှာ data load လုပ်၊ finally ထဲမှာ setLoading(false)။ ဒါမှ request မအောင်မြင်လည်း spinner က ထာဝရ လည်မနေပါဘူး။ Server ဘက်မှာ error log ရေးတဲ့အခါ error type, cause, ဘယ် operation လုပ်နေတုန်းလဲ ဆိုတာ ထည့်ရေးပြီး password, token လို sensitive data ကိုတော့ ဘယ်တော့မှ log ထဲ မထည့်ပါနဲ့။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. Code အများကြီးကို try တစ်ခုထဲ ထည့်ပြီး error တိုင်းကို တစ်မျိုးတည်း ယူဆတာ

စာကြောင်း ငါးဆယ်ကို try တစ်ခုထဲ ထည့်ပြီး catch မှာ "Invalid input" လို့ပဲ ပြရင် ကိုယ့် code ထဲက typo ကြောင့် တက်တဲ့ TypeError ကိုပါ user input မှားတယ်လို့ ပြောမိပါတယ်။ try ကို ပျက်နိုင်တဲ့ စာကြောင်း (ဥပမာ JSON.parse) အနားမှာပဲ ကျဉ်းကျဉ်း ထားပြီး မမျှော်လင့်တဲ့ error အမျိုးအစားကို rethrow လုပ်ပါ။

2. setTimeout ဒါမှမဟုတ် await မလုပ်တဲ့ Promise ကို try က ဖမ်းမယ်လို့ ထင်တာ

try { setTimeout(() => { throw new Error("late"); }, 0); } catch {} မှာ callback က try block ပြီးသွားမှ run လို့ error က uncaught ဖြစ်ပါတယ်။ try { fetchUser(7); } လို့ await မပါဘဲ ရေးရင်လည်း rejection က unhandled ဖြစ်ပါတယ်။ Callback ထဲမှာ ကိုယ်ပိုင် try ထည့်ပါ၊ Promise ဆိုရင် await လုပ်ပါ။

3. finally ထဲမှာ return ရေးတာ

finally { return "done"; } လို့ ရေးရင် try ရဲ့ return value ကိုရော catch ကနေ ပြန်ပစ်တဲ့ error ကိုပါ အစားထိုးပြီး ဖျောက်ပစ်ပါတယ်။ Error တစ်ခု လုံးဝ ပျောက်သွားတဲ့ bug ဖြစ်လို့ finally ကို cleanup အတွက်ပဲ သုံးပြီး return, throw မထည့်ပါနဲ့။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • try block ကို ပျက်နိုင်တဲ့ operation အနားမှာပဲ ကျဉ်းကျဉ်း ထားပါ။
  • String မဟုတ်ဘဲ Error object ကိုပဲ throw လုပ်ပါ၊ ဒါမှ name, message, stack ရပါမယ်။
  • Rethrow လုပ်တဲ့အခါ { cause: error } နဲ့ မူရင်း error ကို ချိတ်ထားပါ။
  • User ကို ပြတဲ့ message ကို ရိုးရှင်းစွာ ရေးပြီး stack trace လို အသေးစိတ်ကို log ထဲမှာပဲ ထားပါ။

Mini challenge

Mini challenge: config parser

Config text ကို parse လုပ်ပြီး malformed JSON နဲ့ field ပျောက်တာကို ခွဲခြားပြောပေးတဲ့ parseConfig() ကို ရေးပါ။ Caller က result object တစ်မျိုးတည်းကိုပဲ ရရပါမယ်။

  • အောင်မြင်ရင် { ok: true, value } ကို ပြန်ပေးရမယ်
  • JSON မမှန်ရင် { ok: false, error: "Malformed JSON" } ကို ပြန်ပေးရမယ်
  • port က number မဟုတ်ရင် { ok: false, error: "Missing field: port" } ကို ပြန်ပေးရမယ်
  • SyntaxError မဟုတ်တဲ့ error ကို rethrow လုပ်ရမယ်
  • finally ကို သုံးပြီး input ဘယ်နှစ်ခု စစ်ပြီးပြီလဲ ရေတွက်ရမယ်
parse-config.js
let processed = 0;

function parseConfig(text) {
  try {
    // TODO: parse the text
    // TODO: return a "Missing field: port" result when port is not a number
    // TODO: return the success result
  } catch (error) {
    // TODO: rethrow anything that is not a SyntaxError
    // TODO: return the "Malformed JSON" result
  } finally {
    // TODO: count this input
  }
}

const inputs = ['{"port": 8080}', '{"port": 8080,}', '{"host": "localhost"}'];
// TODO: print "OK: port <n>" or "Failed: <error>" for each input,
// then "Processed <n> inputs"

ရလဒ်: Console မှာ လေးကြောင်း ထွက်ရပါမယ်: OK: port 8080 Failed: Malformed JSON Failed: Missing field: port Processed 3 inputs

အရိပ်အမြွက် ကြည့်ရန်

JSON.parse က JSON မမှန်ရင် SyntaxError ပစ်ပါတယ်။ catch ထဲမှာ if (!(error instanceof SyntaxError)) throw error; လို့ ရေးပြီး ကျန်တာကိုပဲ ကိုင်တွယ်ပါ။ try ထဲက return ရှိနေလည်း finally က run တာကို မှတ်ထားပါ။

အဖြေ ကြည့်ရန်
parse-config.js
let processed = 0;

function parseConfig(text) {
  try {
    const data = JSON.parse(text);
    if (typeof data.port !== "number") {
      return { ok: false, error: "Missing field: port" };
    }
    return { ok: true, value: data };
  } catch (error) {
    if (!(error instanceof SyntaxError)) throw error; // not ours to handle
    return { ok: false, error: "Malformed JSON" };
  } finally {
    processed += 1;
  }
}

const inputs = ['{"port": 8080}', '{"port": 8080,}', '{"host": "localhost"}'];
for (const text of inputs) {
  const result = parseConfig(text);
  console.log(result.ok ? `OK: port ${result.value.port}` : `Failed: ${result.error}`);
}
console.log(`Processed ${processed} inputs`);

Quick Quiz 1 / 3

function f() { try { return "try"; } finally { console.log("finally"); } } console.log(f()); က ဘာ print ထုတ်မလဲ။

Quick Quiz 2 / 3

try { setTimeout(() => { throw new Error("late"); }, 0); } catch (e) { console.log("caught"); } က ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

loadInvoice() ထဲမှာ database error ဖြစ်ပြီး caller က ဘာမှားလဲ သိဖို့ လိုပါတယ်။ ဘယ် catch block က အကောင်းဆုံးလဲ။

မှတ်ထားရမယ့် အချက်များ

  • try ထဲမှာ error တက်တာနဲ့ ကျန်တဲ့ code ကို ကျော်ပြီး catch ဆီ ရောက်ကာ program က ဆက် run ပါတယ်။
  • finally က return ရှိရှိ error တက်တက် အမြဲ run လို့ cleanup အတွက် သုံးပြီး အထဲမှာ return/throw မထည့်ပါနဲ့။
  • throw new Error(...) နဲ့ business rule ချိုးဖောက်မှုကို ကိုယ်တိုင် ပစ်ရပါတယ် (10 / 0 က error မဟုတ်ပါ)။
  • try...catch က synchronous error နဲ့ await လုပ်ထားတဲ့ rejection ကိုပဲ ဖမ်းပြီး catch တိုင်းမှာ recover ဒါမှမဟုတ် rethrow ဆုံးဖြတ်ပါ။

MDN — JavaScript Guide — MDN Web Docs

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Try...Catch | Thuta Learning