C++;try-catch不适用于超出范围的数组 我们有一个基于Qt的C++应用程序。我们也在使用第三方DLL。但是,C++尝试和捕获根本不起作用。
例如:C++;try-catch不适用于超出范围的数组 我们有一个基于Qt的C++应用程序。我们也在使用第三方DLL。但是,C++尝试和捕获根本不起作用。,c++,exception-handling,C++,Exception Handling,例如: #include <QCoreApplication> #include <QDebug> #include <QException> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); int arr[10]; try { arr[11] = 30; } catch (const std::out_of
#include <QCoreApplication>
#include <QDebug>
#include <QException>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int arr[10];
try
{
arr[11] = 30;
}
catch (const std::out_of_range& e)
{
qDebug() << "Exception out of range occurred ..." << e.what();
}
catch (...)
{
qDebug() << "Unknown Exception occured...";
}
return a.exec();
}
#包括
#包括
#包括
int main(int argc,char*argv[])
{
qcorea应用程序(argc、argv);
int-arr[10];
尝试
{
arr[11]=30;
}
捕获(常数标准::超出范围和e)
{
qDebug()要回答您的问题:
“C++try catch不适用于第三方库”
< C++ >代码>尝试catch <代码>使用第三方(QT >库),如下面的例子所示。
但是您显示的代码不是一个。因此很难说是什么导致了您所说的问题
#include <QCoreApplication>
#include <QDebug>
#include <QException>
class testException : public QException
{
public:
testException(QString const& message) :
message(message)
{}
virtual ~testException()
{}
void raise() const { throw *this; }
testException *clone() const { return new testException(*this); }
QString getMessage() const {
return message;
}
private:
QString message;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
try
{
// throw std::out_of_range("blah");
throw testException("blah");
}
catch (const std::out_of_range& e)
{
qDebug() << "Exception out of range occurred ...";
}
catch (...)
{
qDebug() << "Unknown Exception occured...";
}
return a.exec();
}
#包括
#包括
#包括
类testException:公共QException
{
公众:
testException(QString常量和消息):
消息(消息)
{}
虚拟~testException()
{}
void raise()常量{throw*this;}
testException*clone()常量{返回新的testException(*this);}
QString getMessage()常量{
返回消息;
}
私人:
QString消息;
};
int main(int argc,char*argv[])
{
qcorea应用程序(argc、argv);
尝试
{
//抛出std::超出范围(“废话”);
抛出测试异常(“废话”);
}
捕获(常数标准::超出范围和e)
{
qDebug()
它可能由std::bitset
和std::basic_string
的成员函数抛出,由std::stoi
和std::stod
函数族抛出,也可能由边界检查的成员访问函数抛出(例如std::vector::at
和std::map::at
)
您的try
块没有这两项功能。对普通C样式数组的越界访问是无效的。正如您所经历的,这通常表现为崩溃。读取或写入数组越界是未定义的行为。不能保证它会崩溃、抛出异常或执行任何操作。这只是错误的代码
如果你想要一个像数组一样的容器进行边界检查,可能在标准库中有。它们都有一个执行边界检查的at()
成员函数,将抛出一个std::out\u of_range
异常。试试qDebug()请。例如,您在何处声明m_Qmutex
。编辑示例以获得MCVE,谢谢Joey和Neil。此示例也不太有效,因为与运算符[]超出了界限
和int*
不应引发异常!写入数组边界外是未定义的行为。不需要崩溃、引发异常或执行任何操作。抱歉。在这种情况下,编写std::set\u terminate会有所帮助?@hetalagrawal设置终止处理程序在处理异常时非常有用ils(例如未捕获的std::超出范围)请记住,在一个普通数组中的超出界限是未定义的行为,所以<代码> STD::SETIONESTATEATEAUT/<代码>不是您问题中代码的解决方案。为什么我们不能用C++中的TestCcatch块来处理空指针访问。原因是它导致了未定义的行为吗?@ HealAlgRAWAL:由空指针访问引起的StEngbug不是C++。+例外情况见: