Exception Handling
Quick Notes
Section titled “Quick Notes”Exception dùng để báo lỗi không xử lý được tại chỗ.
Throw object có nghĩa, catch bằng const&.
Không dùng exception cho control flow thường ngày.
Syntax
Section titled “Syntax”try { run();} catch (const std::exception& ex) { std::cerr << ex.what() << '\n';}Example
Section titled “Example”#include <stdexcept>
int divide(int a, int b){ if (b == 0) { throw std::invalid_argument("division by zero"); } return a / b;}Common Types
Section titled “Common Types”| Type | Use |
|---|---|
std::exception | Base exception |
std::runtime_error | Runtime failure |
std::invalid_argument | Tham số không hợp lệ |
std::out_of_range | Index/range không hợp lệ |
Common Mistakes
Section titled “Common Mistakes”- Catch bằng value làm slicing exception.
- Throw raw string thay vì exception type.
- Nuốt lỗi bằng
catch (...)mà không log hoặc xử lý.
Search Keywords
Section titled “Search Keywords”exception handling xử lý ngoại lệ try catch throw std::exception runtime_error invalid_argument