Skip to content

Exception Handling

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.

try {
run();
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
}
#include <stdexcept>
int divide(int a, int b)
{
if (b == 0) {
throw std::invalid_argument("division by zero");
}
return a / b;
}
TypeUse
std::exceptionBase exception
std::runtime_errorRuntime failure
std::invalid_argumentTham số không hợp lệ
std::out_of_rangeIndex/range không hợp lệ
  • 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ý.

exception handling xử lý ngoại lệ try catch throw std::exception runtime_error invalid_argument