有没有办法捕获 STL 函数未被赋予正确参数的异常?
Is there a way to catch the exception of an STL function not being given right arguments?
我正在使用std::stol((将字符串转换为长类型。但是,如果用户输入字母,如何确保捕获异常?
代码可以在这里找到。
注意:我已经找到了这个问题的正确方法,我只需要知道该怎么做,而不是:
if ( !(stol(input)) ) // Yes, I know it's stupid to think the output would be bool
throw 'R';
std::stol()
输入错误时引发异常。使用try..catch
来捕捉它们。
从评论到另一个答案,这里的目标似乎有些模棱两可。为了回答标题中的问题,为了捕获异常,您编写了一个try ... catch
块:
long get_value() {
for (;;) {
std::cout << "Enter a number: ";
std::string text;
std::cin >> text;
try {
return stol(text);
} catch(...) {
std::cout << "Invalid inputn";
}
}
}
但评论表明,扫描整个输入文本以查看任何地方是否有字母的解决方案是合适的。如果目标是要求输入仅包含数字,则无需在调用std::stol
之前扫描每个字符。它比你想象的更聪明。
int last;
std::stol(text, &last);
if (last != text.length())
// got a bad character
这将检测类似"123q"
的输入。
与往常一样,请阅读文档。
相关文章:
- 有没有办法捕获 STL 函数未被赋予正确参数的异常?
- 调用参数不是原子参数的函数是此代码引发异常的原因吗?
- 我正在尝试创建一个使用 c++ 中的参数包构造函数的异常类
- 如何修复"ctypes"。参数错误:参数 2:<键入"异常.类型错误">:RaspberryPi 中的错误类型"错误
- 当构造函数的参数类型错误时引发异常
- 在 Myfile.exe 中0x00831D39时未处理的异常:0xC00000FD:堆栈溢出(参数:0x0000000
- 为什么可以指定异常规范的参数类型
- 如何避免字符串到整数转换情况下的无效参数异常
- basic_string::替换的超出范围异常,而在范围内,正如调试相同参数的输出所证明的那样
- 自动存储中没有无参数构造函数的类对象和异常
- 为什么初始化构造函数列表参数时会发生异常?
- JNI自定义异常具有多个参数
- 防止在将未引发的异常作为参数传递时在"throw e;"中切片
- 传递参数时引发异常
- 如果在可变参数模板解包中达到终止函数,则出现异常
- 与构造函数参数相关的异常安全的习语
- 从 noexcept 函数参数的构造函数引发的异常会立即导致对 std::terminate() 的调用吗?
- 插入>>运算符重载:从 CIN 检索对象的 CTOR 参数时的异常处理
- 接收器参数和异常
- 双指针输出数组参数异常