C++ 异常和报错排查

253 阅读1分钟

先来一份简单的捕获异常示例代码

  • 捕获异常
  • 动态数组的管理
  • 解析errno
    // 文中制造了两处 crash
    #include <fstream>
    #include <memory>
    #include <stdio.h>
    #include <thread>
    #include <iostream>
    
    int main()
    {		
            int file_size = 1024 * 1024 * 100;
            try {
                    // crach 1  
                    std::ifstream ifs("./1.txt");  
                    ifs.exceptions(std::ios::failbit);
                    while (1)
                    {
                            // std::shared_ptr<uint8_t[]> sp_data(new uint8_t[file_size]);  
    
                            // crash 2
                            new uint8_t[file_size];
                            std::this_thread::sleep_for(std::chrono::milliseconds(200));
                            std::cout << "malloc memory once " << std::endl;
                    }
            }
            catch (std::exception& e)
            {
                    printf("std::exception orrcu, error is : %s \n", e.what());
            }
            catch (...)
            {
                    printf("unknown exception orrcu \n");
            }
            // 推荐
            perror("error occur");  
            // 解析errno的方法二
            // printf("decode errno: %s \n", strerror(errno));
            return 0;  
    }