atomically try catch and avoid throw exception

复制代码
#include <assert.h>
#include <atomic>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <thread>
#include <unistd.h>
#include <uuid/uuid.h>

std::string get_time_now()
{
    std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
    time_t raw_time = std::chrono::high_resolution_clock::to_time_t(now);
    struct tm tm_info = *localtime(&raw_time);
    std::stringstream ss;
    ss << std::put_time(&tm_info, "%Y%m%d%H%M%S");
    return ss.str();
}

void divideDemo(int num = 0)
{
    for (int i = -10; i < 10; i++)
    {
        try
        {
            double d = (double)num / (double)i;
            if (d != std::numeric_limits<double>::infinity())
            {
                std::cout << std::setprecision(10) << std::fixed << "In divide " << (double)num / (double)i << std::endl;
            }
        }
        catch (...)
        {            
        }
    }
}

void multiplyX(int num)
{
    try
    {
        for (int i = -10; i < 10; i++)
        {
            std::cout << "In multiply " << i*num << std::endl;
        }
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }
}

void mt_try_catch(int num)
{
    try
    {
        std::thread t1(divideDemo, num);
        t1.join();
        std::thread t2(multiplyX, num);        
        t2.join();
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }

    std::cout << get_time_now() << ",finish in " << __FUNCTION__ << std::endl;
}

int main(int args, char **argv)
{
    mt_try_catch(atoi(argv[1]));
}
复制代码
//Compile:
g++ -std=c++2a -I. *.cpp -o h1 -luuid -lpthread;
//Run
./h1 10;

 

posted @   FredGrit  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2021-05-08 C++ append file via ofstream
点击右上角即可分享
微信分享提示