C 获取std :: out_of_range异常的位置
C++ Getting Location of std::out_of_range Exceptions
我正在研究一个相当冗长的程序,在运行良好一段时间后,我突然得到了:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
是异常处理的新手,我进行了一些研究,发现我可能会通过将以下内容添加到我的主要功能中获取更多信息:
int main(int argc, char **argv){
try{
//stuff
}
catch(exception const &exc){
cerr << "Caught exception: " << exc.what() << endl;
}
}
结果是以下输出:
Caught exception: basic_string::substr
这并不比默认输出更有用。它没有告诉我有关触发核心转储的行的任何信息(我的程序中有许多substr调用(,substr试图处理的数据等。是否有一种在C 中显示此类信息的方法我唯一使用调试器(例如GDB(的选项是?
有几种方法。
-
正如您所说的,调试器 - 但一旦代码在生产中,这对您没有帮助。
-
嵌套异常和功能尝试块。例如:
&nbsp;
#include <exception>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <iomanip>
void bar(std::string& s, int i)
try
{
s.at(i) = 'A';
}
catch(...)
{
std::ostringstream ss;
ss << "error in bar(" << std::quoted(s) << ", " << i << ")";
std::throw_with_nested(std::runtime_error(ss.str()));
}
void foo(std::string& s)
try
{
bar(s, 6);
}
catch(...)
{
std::ostringstream ss;
ss << "error in foo(" << std::quoted(s) << ")";
std::throw_with_nested(std::runtime_error(ss.str()));
}
void stuff()
try
{
std::string s;
foo(s);
}
catch(...)
{
std::throw_with_nested(std::runtime_error("error in stuff()"));
}
void print_exception(std::ostream& os, const std::exception& e, int level = 0)
{
os << std::string(level, ' ') << "exception: " << e.what() << 'n';
try {
std::rethrow_if_nested(e);
} catch(const std::exception& e) {
print_exception(os, e, level+1);
} catch(...) {}
}
int main()
{
try{
stuff();
}
catch(std::exception& e)
{
print_exception(std::cerr, e);
return 127;
}
return 0;
}
样本输出:
exception: error in stuff()
exception: error in foo("")
exception: error in bar("", 6)
exception: basic_string::at: __n (which is 6) >= this->size() (which is 0)
- 您可以使用
boost::stacktrace
代替上述异常处理。
http://coliru.stacked-crooked.com/a/f21bd35632a0a036
相关文章:
- (此函数用于计算 SMA).在 FA.exe 中0x00509159引发异常: 0xC0000005:访问冲突读取位置0
- 内存位置出现Microsoft C++异常:std::out_of_range
- 0x0F50DF58:0xC0000005:访问冲突读取位置0x0047CA04时未处理的异常
- 错误 在测试.exe 0x76C9FD62时出现未经处理的异常:Microsoft C++异常:内存位置0x006FF8
- 如何找出浮点异常的位置
- C 获取std :: out_of_range异常的位置
- cv:内存位置的异常 - 运行 openCV 代码 Visual Studio 2013 & Visual Studio 2017 - Windows 7
- Microsoft C++异常runtime_error在内存位置(代码 0x75A818A2)
- 在 "<name>.exe" 中0x00007FFF168E1657 (vcruntime140d.dll) 引发异常:0xC0000005:访问冲突写入位置0x0000000000000
- 未经治疗的异常访问违规写作位置
- cv::内存位置出现异常错误
- 如何在 VS C++ 中查找发生异常的位置
- 在cv::Mat对象上循环时,内存位置出现cv::异常
- 如何修复<程序名称>中的"<内存位置>未处理的异常。Visual Studio 2017 中的访问冲突写入位置<内存位置>"
- OpenGL:glDrawArrays()引发异常(nvoglv32.dll)读取位置0x00000000时发生访问冲突
- ***读取位置*******的访问冲突处出现未处理的异常
- 在2.exe中的0x00DE181818的未经手法异常:0xc0000005:访问违规写作位置0xcd7cbe10
- NVIDIA 在 <work.exe>0xC0000005 中0x002a2da2未处理的异常:访问违规读取位置0x00000000
- 未处理的异常..访问冲突写入位置
- 在 DirectXGame.exe 中0x00B84CD6出现未经处理的异常:0xC0000005:访问冲突读取位置0x