C++开发学习笔记(一)

第一步打算跑通机器人的各个组件,并学习C++,让AI先给我写了个yolo识别的demo,然后开始改,看着看着感觉知识点有点多,脑子有点装不下了,索性写个学习笔记吧。

C++ 异常抛出

这个看起来真是又熟悉又陌生,在 python 中有try - except 语句,还有一个finally释放内存,但是cpp中有RAII,异常抛出的时候自动调用析构函数,finally倒是省了,谈谈 try,catch,throw吧。

C++ Python
try try
catch except
raise throw
e e.what()
const std::exception& Exception
1. 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <stdexcept>

class MyError : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};

void f() {
throw MyError("bad");
}

int main() {
try {
f();
} catch (const MyError& e) {
std::cout << e.what() << '\n';
throw;
} catch (const std::exception& e) {
std::cout << "other: " << e.what() << '\n';
} catch (...) {
std::cout << "unknown exception\n";
}
}

这里写了一个myerror继承自runtime_error,并在函数f中抛出,然后在catch块中打印异常结果,基本结构是一样的。

2. 异常类型

stdexcept中提供了很多丰富的类型:

名称 类型
std::exception 所有标准异常类的基类
std::bad_exception 当异常处理过程中发生错误时抛出
std::bad_alloc 当内存分配失败时抛出
std::bad_cast 当类型转换失败时抛出
std::bad_typeid 当 typeid 操作失败时抛出
std::logic_error 当逻辑错误发生时抛出,例如无效的输入参数
std::domain_error 当函数调用的参数不在有效范围内时抛出
std::invalid_argument 当函数调用的参数无效时抛出
std::length_error 当容器操作因为长度限制而失败时抛出
std::out_of_range 当访问容器的非法索引时抛出
std::overflow_error 当算术运算导致溢出时抛出
std::range_error 当函数返回值不在期望的范围内时抛出
std::underflow_error 当算术运算导致下溢时抛出

需要说明的是throw可以接异常类型也可以接函数变量等

3. noexcept

这个关键字是cpp独有的,在后面修饰函数:

1
void f() noexcept;

可以显式声明函数不抛出异常。但当该函数异常时,直接调用std::terminate中止进程。

4. Myexception

写派生异常时需要重写what方法返回异常信息:

1
2
3
4
5
6
class MyException : public std::exception {  
public:
    const char* what() const noexcept {
        return "My custom exception";
    }
};
5. 常用写法
  • catch (…) 是固定搭配,表示捕获任意类型的C++异常。
  • 在catch 中 throw,表示把原来的异常继续抛出去。

参考资料


C++开发学习笔记(一)
http://blog.mingxuan.xin/2026/09/28/20260913/
作者
Obscure
发布于
2026年9月28日
许可协议