函数抛出异常学习

lypbendlf / 2023-07-26 / 原文

转自:https://blog.csdn.net/u014694994/article/details/79074566

1、例子

stoi当字符串不符合规范时,会抛出异常。

#include <stdexcept>
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    std::string y = "253647586946334221002101219955219971002";
    int x;
 
    try {
        x = stoi(y);
    }
    catch (std::invalid_argument&){
        // if no conversion could be performed
        cout << "Invalid_argument" << endl;
    }
    catch (std::out_of_range&){
        // if the converted value would fall out of the range of the result type 
        // or if the underlying function (std::strtol or std::strtoull) sets errno 
        // to ERANGE.
        cout << "Out of range" << endl;
    }
    catch (...) {
        // everything else
        cout << "Something else" << endl;
    }
    return 0;
}

运行之后输出:Out of range。说明stoi函数抛出异常,并被捕获。它可能会抛出std::invalid_argument和std::out_of_range异常。

当y中包含字母无法转换为数字时,会抛出std::out_of_range异常,打印结果为:Invalid_argument。(已测试)

 https://en.cppreference.com/w/cpp/string/basic_string/stol

 如果没有try-catch结构捕获异常会发生什么呢?如下:

-> % ./Demo              
libc++abi: terminating with uncaught exception of type std::out_of_range: stoi: out of range
[1]    31182 abort      ./Demo

 会发生coredump,程序异常退出。