Thuta Learning
C++
AdvancedProgrammingအခြေခံ

Exceptions (Try...Catch)

C++သင်ခန်းစာ 2435 မိနစ်

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

  • Function တစ်ခုထဲကနေ standard exception ကို throw လုပ်ပြီး caller ဘက်မှာ try/catch နဲ့ ကိုင်တွယ်နိုင်ဖို့
  • Exception ကို value နဲ့ throw ပြီး const reference နဲ့ catch ဖမ်းရတဲ့ အကြောင်းရင်းကို ရှင်းပြနိုင်ဖို့
  • std::exception hierarchy ထဲက မှန်ကန်တဲ့ type ကို ရွေးပြီး catch clause တွေကို specific ကနေ general အစဉ်နဲ့ စီနိုင်ဖို့
  • Stack unwinding အတွင်း RAII object တွေက resource ကို ဘယ်လို လွှတ်ပေးလဲ ခန့်မှန်းနိုင်ဖို့
  • noexcept ရဲ့ အဓိပ္ပာယ်နဲ့ destructor ထဲကနေ exception မထွက်စေရတဲ့ အကြောင်းကို ပြောနိုင်ဖို့

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

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

စားသောက်ဆိုင်တစ်ခုမှာ စားဖိုမှူးက ကြက်သား ကုန်သွားတာကို သိတဲ့အခါ စားပွဲထိုးကို ဒါမှမဟုတ် manager ကို အသိပေးပါတယ်။ စားဖိုမှူးကိုယ်တိုင် customer ဆီ သွားပြီး menu ပြောင်းဖို့ စကားပြောမနေပါဘူး — ပြဿနာကို ဖြေရှင်းနိုင်တဲ့ လူဆီ လှမ်းပို့လိုက်တာပါ။

C++ မှာ ဒီလို လှမ်းပို့တာကို throw လို့ ခေါ်ပါတယ်။ ဆက်လုပ်လို့ မရတဲ့ function က exception object တစ်ခုကို throw လုပ်ပြီး ချက်ချင်း ရပ်သွားပါတယ်။ Function ကို ခေါ်ထားတဲ့ ဘက်က try block နဲ့ "ဒီအထဲမှာ ပြဿနာ ဖြစ်နိုင်တယ်" လို့ မှတ်ထားပြီး catch block က အဲဒီ exception ကို ဖမ်းကာ ကိုင်တွယ်ပါတယ်။

Problem → Why → Solution

ပြဿနာ: error code ကို စစ်ဖို့ မေ့သွားတာ

Exception မသုံးဘဲ error ကို -1 လို special value နဲ့ ပြန်ပေးတာ အဖြစ်များပါတယ်။ အောက်က parsePort() က မှားတဲ့ text အတွက် -1 ကို မှန်မှန်ကန်ကန် ပြန်ပေးပါတယ်။ ပြဿနာက caller က စစ်ဖို့ မေ့သွားတာပါ — program က ဆက် run ပြီး server ကို port -1 မှာ စဖို့ ကြိုးစားပါတယ်။

error_code.cpp
#include <iostream>
#include <string>

// Returns the port, or -1 when the text is not a valid port number.
int parsePort(const std::string& text) {
    if (text.empty() || text.size() > 5) return -1;
    for (char c : text) if (c < '0' || c > '9') return -1;
    int port = std::stoi(text);
    return (port >= 1 && port <= 65535) ? port : -1;
}

void startServer(int port) { std::cout << "listening on port " << port << '\n'; }

int main() {
    int port = parsePort("80a");
    startServer(port);        // nobody checked: "listening on port -1"
}

ဘာကြောင့် error code တွေက လွတ်သွားလွယ်တာလဲ

Return value ကို စစ်ဖို့ compiler က မတောင်းဆိုပါဘူး၊ ဒါကြောင့် စစ်ဖို့ မေ့တာ ဘာ error မှ မပေးဘဲ မှားတဲ့ data နဲ့ ဆက် run ပါတယ်။ Call chain နက်လာရင် အလွှာတိုင်းက error ကို စစ်ပြီး အပေါ်ကို လက်နဲ့ ဆက်ပို့ရပြီး constructor လို return value မရှိတဲ့ function တွေက error code ကို ပြန်ပေးလို့ကို မရပါဘူး။ Exception ကိုတော့ လျစ်လျူရှုလို့ မရပါဘူး — ဘယ်သူမှ မဖမ်းရင် program က မှားတဲ့ data နဲ့ ဆက်မ run ဘဲ ရပ်သွားပါတယ်။

Core concept: throw → stack unwinding → catch

throw expression တစ်ခု run တဲ့အခါ exception object တစ်ခု ဆောက်ပြီး လက်ရှိ function ရဲ့ ကျန်တဲ့ code ကို ကျော်ပါတယ်။ ပြီးရင် runtime က call stack ကို အပေါ်ဘက် (caller တွေဘက်) ပြန်တက်ပြီး ဖြတ်သွားတဲ့ function တိုင်းရဲ့ local object တွေကို destructor ခေါ်ကာ ဖျက်ပါတယ် — ဒါကို stack unwinding လို့ ခေါ်ပါတယ်။ Exception type နဲ့ ကိုက်တဲ့ catch handler ပါတဲ့ try block ကို တွေ့တဲ့အထိ ဆက်သွားပြီး handler ကို run ပါတယ်။ ဘယ်နေရာမှာမှ handler မတွေ့ရင် std::terminate ကို ခေါ်ပြီး program ရပ်ပါတယ်။

Exception ကို value နဲ့ throw ပြီး const reference နဲ့ catch ဖမ်းပါ — throw std::invalid_argument("..."); နဲ့ catch (const std::exception& e) ပုံစံပါ။ Value နဲ့ catch ဖမ်းရင် exception ကို copy ကူးပြီး derived အပိုင်းကို slicing နဲ့ ဖြတ်ပစ်လို့ e.what() က မှန်ကန်တဲ့ message ကို မပြနိုင်တော့ပါဘူး။ Reference ကတော့ copy မကူးဘဲ object ရဲ့ dynamic type ကို ထိန်းထားလို့ virtual what() က တကယ့် message ကို ပြန်ပေးပါတယ်။

Exception typeဆင်းသက်တာပုံမှန် အကြောင်းရင်း
std::invalid_argumentstd::logic_errorFunction ရဲ့ စည်းကမ်းနဲ့ မကိုက်တဲ့ argument
std::out_of_rangestd::logic_errorvector::at() ကို index မှားပေးတာ
std::runtime_errorstd::exceptionRun မှ သိနိုင်တဲ့ ပြဿနာ (network၊ file)
std::bad_allocstd::exceptionnew က memory မရတာ

Catch clause တွေကို အပေါ်ကနေ အောက် အစဉ်လိုက် စစ်ပြီး ပထမဆုံး ကိုက်တဲ့ တစ်ခုကိုပဲ run ပါတယ်။ Derived type က base type handler နဲ့လည်း ကိုက်လို့ specific (derived) type တွေကို အရင်ရေးပြီး const std::exception& ကို နောက်ဆုံးမှာ ထားပါ။ catch (...) က ဘာမဆို ဖမ်းပြီး handler ထဲမှာ throw; လို့ ရေးရင် လက်ရှိ exception ကို မူလ type အတိုင်း ပြန် throw ပါတယ်။ ကိုယ်ပိုင် exception type လိုရင် std::runtime_error စတဲ့ standard class တစ်ခုကနေ ဆင်းသက်စေပါ၊ ဒါမှ const std::exception& handler တွေက ဖမ်းနိုင်ပါမယ်။

Exception တွေကို ပုံမှန် ဖြစ်နေကျ အခြေအနေ (loop ပြီးတာ၊ user က "no" ရွေးတာ) အတွက် မသုံးပါနဲ့။ Function က သူ့အလုပ်ကို မလုပ်နိုင်တဲ့ တကယ့် failure တွေ — invalid input၊ ပျောက်နေတဲ့ file၊ invariant မတည်ဆောက်နိုင်တဲ့ constructor — အတွက်ပဲ သုံးပါ။

မှတ်ထားရမယ့် ပုံစံ: throw၊ unwind၊ catch
  1. Failure တွေ့ရင် object တစ်ခု throw
  2. Unwind: code ကျော်၊ local တွေ ဖျက်
  3. Catch clause တွေကို အပေါ်ကနေ စစ်
  4. သင့်တော်တဲ့ အဆင့်မှာ တစ်ခါပဲ ကိုင်

Exception ကို ဖြစ်တဲ့ နေရာမှာ throw ပြီး တကယ် ဆုံးဖြတ်ချက် ချနိုင်တဲ့ နေရာမှာမှ catch ဖမ်းပါ — ကြားက function တွေက ဘာမှ ရေးစရာ မလိုပါဘူး။

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

cpp
Result mightFail(Input value) {
    if (cannotSucceed(value))
        throw std::runtime_error("what went wrong");   // throw by value
    return result;
}
try {
    use(mightFail(input));
} catch (const SpecificError& e) {      // most specific type first
    handle(e);
} catch (const std::exception& e) {     // catch by const reference
    report(e.what());
}

Function က ဆက်လုပ်လို့ မရတဲ့အခါ standard exception type တစ်ခုကို throw လုပ်ပါတယ်။ Caller က try block ထဲမှာ ခေါ်ပြီး specific type ကို အရင်၊ std::exception ကို နောက်ဆုံး catch ဖမ်းပါတယ်။ Handler တိုင်းက const reference ကို သုံးပါတယ်။

Example: အသက် စစ်ဆေးခြင်း

ဒီ example မှာ checkAge() က အသက် 18 မပြည့်ရင် std::invalid_argument ကို throw လုပ်ပါတယ်။ Exception က function နယ်နိမိတ်ကို ကျော်ပြီး main() ထဲက catch ဆီ ရောက်သွားတာနဲ့ "Access granted." line ကို ကျော်သွားတာကို သတိထားကြည့်ပါ။

exceptions.cpp
#include <iostream>
#include <stdexcept>
using namespace std;

void checkAge(int age) {
    if (age < 18) {
        throw invalid_argument("You must be at least 18 years old.");
    }
}

int main() {
    try {
        int age = 15;
        checkAge(age);
        cout << "Access granted." << endl;
    } catch (const invalid_argument& e) {
        cout << "Access denied: " << e.what() << endl;
    }
    return 0;
}

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

  1. Line 2#include <stdexcept>

    std::invalid_argument၊ std::runtime_error စတဲ့ standard exception class တွေ ဒီ header ထဲမှာ ရှိပါတယ်။

  2. Line 7throw invalid_argument("You must be at least 18 years old.");

    Exception object ကို value နဲ့ ဆောက်ပြီး throw ပါတယ်။ checkAge() က ဒီနေရာမှာ ချက်ချင်း ရပ်ပြီး return ပြန်တာ မဟုတ်ဘဲ unwinding စပါတယ်။

  3. Lines 14-15checkAge(age);

    Exception က checkAge() ကနေ main() ရဲ့ try block ထဲ ပြန်ရောက်လာပါတယ်။ နောက် line ဖြစ်တဲ့ "Access granted." ကို လုံးဝ မ run တော့ပါဘူး။

  4. Line 16} catch (const invalid_argument& e) {

    Type ကိုက်လို့ ဒီ handler က run ပါတယ်။ const reference ဖြစ်လို့ copy မကူးဘဲ slicing လည်း မဖြစ်ပါဘူး။

  5. Line 17e.what()

    what() က std::exception ရဲ့ virtual member function ဖြစ်ပြီး constructor ကို ပေးခဲ့တဲ့ message ကို ပြန်ပေးလို့ "Access denied: You must be at least 18 years old." ထွက်ပါတယ်။

You should see
Access denied: You must be at least 18 years old.
throw ပြီးနောက် ဖြစ်ပျက်ပုံ
  1. throw က exception object ကို ဆောက်
  2. checkAge() ရဲ့ ကျန်တဲ့ code ကို ကျော်
  3. Unwind လုပ်ရင်း local တွေကို ဖျက်
  4. ပထမဆုံး ကိုက်တဲ့ catch ကို run

Handler ကိုက်တယ်

catch runs, program continues

Handler ဘယ်မှာမှ မရှိ

std::terminate ends the program

Standard hierarchy နဲ့ catch အစဉ်

Standard library ကိုယ်တိုင်လည်း exception တွေ throw လုပ်ပါတယ်။ vector::at() က index မှားရင် std::out_of_range၊ std::stoi() က number မဟုတ်တဲ့ text ကို std::invalid_argument throw လုပ်ပါတယ်။ အောက်က program မှာ catch clause သုံးခုကို specific ကနေ general အစဉ်နဲ့ စီထားပါတယ် — invalid_argument က logic_error ကနေ ဆင်းသက်လို့ ဒုတိယ handler က ဖမ်းပါတယ်။

hierarchy.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

void run(int test) {
    std::vector<int> scores{90, 75};
    if (test == 0) std::cout << scores.at(5) << '\n';        // out_of_range
    if (test == 1) std::cout << std::stoi("abc") << '\n';    // invalid_argument
    if (test == 2) throw std::runtime_error("database is offline");
}

int main() {
    for (int test = 0; test < 3; ++test) {
        try {
            run(test);
        } catch (const std::out_of_range&) {
            std::cout << "index problem\n";
        } catch (const std::logic_error&) {
            std::cout << "logic error\n";
        } catch (const std::exception& e) {
            std::cout << "other error: " << e.what() << '\n';
        }
    }
}

Output က "index problem"၊ "logic error"၊ "other error: database is offline" ပါ။ at() နဲ့ stoi() ရဲ့ what() message တွေကတော့ standard library implementation အလိုက် ကွာနိုင်လို့ ဒီ program က print မထုတ်ပါဘူး။ const std::exception& handler ကို ပထမဆုံး ရွှေ့လိုက်ရင် အားလုံးကို အဲဒါက ဖမ်းသွားပြီး g++ က "will be caught by earlier handler" လို့ သတိပေးပါတယ်။

RAII: exception ကြားကလည်း cleanup ဖြစ်စေခြင်း

Stack unwinding က local object တွေရဲ့ destructor ကို ခေါ်ပေးလို့ resource ကို destructor ထဲမှာ လွှတ်ပေးတဲ့ RAII class တွေက exception ဖြစ်ဖြစ် မဖြစ်ဖြစ် cleanup ကို အာမခံပါတယ် (lesson 16)။ အောက်က Connection က constructor မှာ "open" ပြီး destructor မှာ "close" လုပ်ပါတယ်။ saveOrder(-1) က throw လုပ်တဲ့အခါ db ကို ပိတ်ပေးတာကို output မှာ တွေ့ရပါတယ်။

raii_unwinding.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>

class Connection {
public:
    explicit Connection(std::string name) : name_(std::move(name)) {
        std::cout << "open " << name_ << '\n';
    }
    ~Connection() { std::cout << "close " << name_ << '\n'; }

private:
    std::string name_;
};

void saveOrder(int id) {
    Connection db("orders-db");
    if (id < 0) throw std::invalid_argument("negative order id");
    std::cout << "saved order " << id << '\n';
}

int main() {
    try {
        saveOrder(7);
        saveOrder(-1);
        saveOrder(8);            // never reached
    } catch (const std::exception& e) {
        std::cout << "error: " << e.what() << '\n';
    }
}

Output က "open orders-db"၊ "saved order 7"၊ "close orders-db"၊ "open orders-db"၊ "close orders-db"၊ "error: negative order id" ပါ။ ဒုတိယ "close" က catch handler မ run ခင် ထွက်လာတာကို သတိထားပါ — unwinding က handler ဆီ မရောက်ခင် local တွေကို ဖျက်ပြီးသွားပါပြီ။ new နဲ့ delete ကို လက်နဲ့ ရေးထားရင်တော့ throw နဲ့ delete ကြားမှာ ကျော်သွားပြီး memory leak ဖြစ်ပါတယ်၊ ဒါကြောင့် ownership ကို std::unique_ptr လို RAII type တွေနဲ့ ကိုင်ပါ။

noexcept နဲ့ destructor များ

Function တစ်ခုကို noexcept လို့ မှတ်ရင် "ဒီ function က exception ဘယ်တော့မှ မထွက်ဘူး" လို့ ကတိပေးတာပါ။ ကတိ ချိုးပြီး exception ထွက်လာရင် std::terminate ကို ခေါ်ပြီး program ရပ်ပါတယ်။ ဒီကတိက performance အတွက်လည်း အရေးကြီးပါတယ် — std::vector က memory ပြန်ချဲ့တဲ့အခါ element ရဲ့ move constructor က noexcept ဖြစ်မှသာ copy ကူးမယ့်အစား move လုပ်ပါတယ်။

Destructor တွေက ကိုယ်တိုင် မရေးရင်တောင် default အနေနဲ့ noexcept ဖြစ်ပါတယ်။ ဒါကြောင့် destructor ထဲကနေ exception ထွက်ရင် std::terminate ဖြစ်ပြီး g++ ကလည်း "'throw' will always call 'terminate'" လို့ သတိပေးပါတယ်။ Unwinding လုပ်နေတုန်း exception နှစ်ခု တစ်ပြိုင်နက် ရှိနေလို့ မရတာကြောင့် ဒီစည်းမျဉ်း ရှိတာပါ။ Destructor ထဲမှာ မအောင်မြင်နိုင်တဲ့ cleanup ရှိရင် အတွင်းမှာပဲ ဖမ်းပြီး log လုပ်ပါ၊ caller က error ကို သိဖို့ လိုရင် exception throw လုပ်လို့ရတဲ့ close() function ကို သီးခြား ပေးပါ။

noexcept.cpp
#include <iostream>
#include <string>
#include <type_traits>

int add(int a, int b) noexcept { return a + b; }
int parse(const std::string& text) { return std::stoi(text); }

struct Widget {
    ~Widget() {}        // destructors are noexcept unless you say otherwise
};

int main() {
    std::cout << std::boolalpha;
    std::cout << "add: " << noexcept(add(1, 2)) << '\n';
    std::cout << "parse: " << noexcept(parse("7")) << '\n';
    std::cout << "~Widget: " << std::is_nothrow_destructible_v<Widget> << '\n';
}

noexcept(expression) operator က expression ကို run မလုပ်ဘဲ exception ထွက်နိုင်လား compile time မှာ စစ်ပါတယ်။ Output က "add: true"၊ "parse: false"၊ "~Widget: true" ဖြစ်ပြီး Widget ရဲ့ destructor မှာ noexcept မရေးထားပေမယ့် true ထွက်တာကို သတိထားပါ။

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

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

Web server တွေမှာ request handler တစ်ခုစီရဲ့ အပြင်ဆုံး အလွှာမှာ catch (const std::exception& e) တစ်ခု ထားလေ့ ရှိပါတယ်။ Request တစ်ခု မအောင်မြင်ရင် error ကို log ထဲ ရေးပြီး client ကို HTTP 500 ပြန်ပို့ကာ server ကတော့ ဆက် run ပါတယ်။ အတွင်းပိုင်း function တွေက ဒီ handler ရှိနေတာကို သိစရာ မလိုဘဲ ပြဿနာ ဖြစ်တဲ့ နေရာမှာ throw ရုံပါပဲ။ Database connection၊ file နဲ့ lock တွေကို RAII နဲ့ ကိုင်ထားလို့ request ပျက်သွားတိုင်း resource ယိုစိမ့်တာ မဖြစ်ပါဘူး။

အချို့ codebase တွေကတော့ exception ကို လုံးဝ မသုံးပါဘူး — ဥပမာ Google C++ Style Guide က exception မသုံးဖို့ ဆုံးဖြတ်ထားပြီး embedded system နဲ့ game engine အချို့က -fno-exceptions နဲ့ compile လုပ်ပါတယ်။ အဲဒီလို နေရာတွေမှာ error code၊ std::optional ဒါမှမဟုတ် C++23 ရဲ့ std::expected ကို သုံးကြပါတယ်။ ဘယ်နည်းကို ရွေးရွေး project တစ်ခုလုံးမှာ တစ်မျိုးတည်း တသမတ်တည်း သုံးတာ အရေးကြီးပါတယ်။

အမှားများ

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

1. Value နဲ့ catch ဖမ်းတာ

catch (std::exception e) က exception ကို copy ကူးပြီး slicing ဖြစ်စေပါတယ်။ g++ -Wall က "catching polymorphic type 'class std::exception' by value [-Wcatch-value=]" လို့ သတိပေးပြီး GCC ရဲ့ standard library မှာ copy ရဲ့ what() က message အစစ်အစား "std::exception" ပဲ ပြန်ပေးပါတယ်။ catch (const std::exception& e) လို့ အမြဲ ရေးပါ။

2. General handler ကို အရင် ရေးတာ

catch (const std::exception&) ကို catch (const std::invalid_argument&) ရဲ့ အပေါ်မှာ ထားရင် invalid_argument အားလုံးကို ပထမ handler က ဖမ်းသွားပြီး ဒုတိယ handler ဘယ်တော့မှ မ run ပါဘူး။ g++ က "exception of type 'std::invalid_argument' will be caught by earlier handler [-Wexceptions]" warning ပေးပါတယ်။ Derived type တွေကို အရင် ရေးပါ။

3. Destructor ထဲကနေ throw လုပ်တာ

~Connection() { throw std::runtime_error("close failed"); } က destructor ရဲ့ implicit noexcept ကြောင့် std::terminate ကို ခေါ်ပြီး program ကို ချက်ချင်း ရပ်စေပါတယ်။ g++ က "'throw' will always call 'terminate' [-Wterminate]" လို့ သတိပေးပါတယ်။ Destructor ထဲမှာ error ကို ဖမ်းပြီး log လုပ်ပါ။

4. string ဒါမှမဟုတ် int ကို throw လုပ်တာ

throw std::string("failed"); ဒါမှမဟုတ် throw 42; က တရားဝင်ပေမယ့် std::exception ကနေ မဆင်းသက်လို့ catch (const std::exception&) လို generic handler တွေက မဖမ်းနိုင်ပါဘူး၊ what() လည်း မရှိပါဘူး။ Standard exception type ဒါမှမဟုတ် အဲဒါကနေ ဆင်းသက်တဲ့ ကိုယ်ပိုင် class ကို throw လုပ်ပါ။

Best Practices

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

  • Exception ကို value နဲ့ throw ပြီး const reference နဲ့ catch ဖမ်းပါ။
  • Error ကို တကယ် ကိုင်တွယ်နိုင်တဲ့ နေရာမှာပဲ catch ဖမ်းပါ၊ ဖမ်းပြီး ဘာမှ မလုပ်ဘဲ ထားခဲ့တဲ့ (empty) catch block မရေးပါနဲ့။
  • Resource တိုင်းကို RAII object နဲ့ ကိုင်ပြီး လက်နဲ့ cleanup လုပ်တာကို ရှောင်ပါ။
  • Move constructor၊ swap နဲ့ destructor တွေကို noexcept ထားပြီး exception မထွက်အောင် ရေးပါ။

Mini challenge

Mini challenge: port number ကို exception နဲ့ စစ်ခြင်း

Text ကနေ port number ကို ဖတ်တဲ့ parsePort() ကို error code အစား exception နဲ့ ပြန်ရေးပြီး input ငါးခုနဲ့ စမ်းပါ။

  • Text အလွတ် ဒါမှမဟုတ် digit မဟုတ်တဲ့ character ပါရင် std::invalid_argument ကို throw ရမယ်
  • 1 ကနေ 65535 အပြင်ဘက် ဖြစ်ရင် (digit 5 လုံးထက် ရှည်တာ အပါအဝင်) std::out_of_range ကို throw ရမယ်
  • main() က input တစ်ခုစီကို try ထဲမှာ ခေါ်ပြီး exception type နှစ်မျိုးကို သီးခြား catch ဖမ်းရမယ် (const reference နဲ့)
  • နောက်ဆုံးမှာ input ဘယ်နှခု လက်ခံခဲ့လဲ print ထုတ်ရမယ်
ports.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

int parsePort(const std::string& text) {
    // TODO: empty text           -> std::invalid_argument("empty input")
    // TODO: a non-digit character -> std::invalid_argument("'<text>' is not a number")
    // TODO: outside 1..65535      -> std::out_of_range("<text> is outside 1-65535")
    // TODO: otherwise return the port
}

int main() {
    const std::vector<std::string> inputs{"8080", "80a", "70000", "", "0"};
    // TODO: for each input: try parsePort, print "port N" or the error,
    //       catching invalid_argument and out_of_range separately
    // TODO: print "<accepted> of <total> inputs accepted"
}

ရလဒ်: Program က အောက်ပါအတိုင်း print ထုတ်ရပါမယ်: port 8080 invalid: '80a' is not a number out of range: 70000 is outside 1-65535 invalid: empty input out of range: 0 is outside 1-65535 1 of 5 inputs accepted

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

std::stoi ကို မခေါ်ခင် character တိုင်း '0' နဲ့ '9' ကြား ဖြစ်လား စစ်ပါ — std::stoi("80a") က 80 ကို ပြန်ပေးပြီး exception မ throw လို့ပါ။ Text အရှည် 5 ထက် ကျော်ရင် stoi မခေါ်ခင် out_of_range throw လုပ်လိုက်ရင် int overflow ကိုလည်း ရှောင်ပြီးသား ဖြစ်ပါတယ်။

အဖြေ ကြည့်ရန်
ports.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

int parsePort(const std::string& text) {
    if (text.empty()) throw std::invalid_argument("empty input");
    for (char c : text) {
        if (c < '0' || c > '9') {
            throw std::invalid_argument("'" + text + "' is not a number");
        }
    }
    if (text.size() > 5) throw std::out_of_range(text + " is outside 1-65535");
    int port = std::stoi(text);
    if (port < 1 || port > 65535) throw std::out_of_range(text + " is outside 1-65535");
    return port;
}

int main() {
    const std::vector<std::string> inputs{"8080", "80a", "70000", "", "0"};
    int accepted = 0;
    for (const auto& input : inputs) {
        try {
            int port = parsePort(input);
            std::cout << "port " << port << '\n';
            ++accepted;
        } catch (const std::invalid_argument& e) {
            std::cout << "invalid: " << e.what() << '\n';
        } catch (const std::out_of_range& e) {
            std::cout << "out of range: " << e.what() << '\n';
        }
    }
    std::cout << accepted << " of " << inputs.size() << " inputs accepted\n";
}

Quick Quiz 1 / 3

try { std::cout << "A"; throw std::runtime_error("x"); std::cout << "B"; } catch (const std::exception&) { std::cout << "C"; } std::cout << "D"; က ဘာ print ထုတ်မလဲ။

Quick Quiz 2 / 3

std::runtime_error ကို ဖမ်းဖို့ ဘယ် catch clause က အကောင်းဆုံးလဲ။

Quick Quiz 3 / 3

noexcept လို့ မှတ်ထားတဲ့ function ထဲကနေ exception ထွက်လာရင် ဘာဖြစ်မလဲ။

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

  • throw က function ကို ရပ်ပြီး stack ကို unwind လုပ်ကာ ကိုက်တဲ့ ပထမဆုံး catch ကို ရှာပါတယ်၊ မတွေ့ရင် std::terminate ဖြစ်ပါတယ်။
  • Standard exception type တွေကို value နဲ့ throw ပြီး const reference နဲ့ specific ကနေ general အစဉ်နဲ့ catch ဖမ်းပါ။
  • Unwinding က local object တွေရဲ့ destructor ကို ခေါ်လို့ RAII က exception ကြားက cleanup ကို အာမခံပါတယ်။
  • noexcept ကို ချိုးရင် std::terminate ဖြစ်ပြီး destructor တွေက default noexcept ဖြစ်လို့ အဲဒီထဲကနေ exception ဘယ်တော့မှ မထွက်စေရပါ။

C++ Core Guidelines — Standard C++ Foundation

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

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

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

Exceptions (Try...Catch) | Thuta Learning