在下面的代碼中,我在python模塊代碼中使用try/catch
。在try
塊中,我有一個簡單的錯誤(內存訪問衝突),並試圖捕獲相應的異常並安靜地終止程序,而不生成.stackdump
文件。然而,後者仍然生成暗示try/catch
構造不能完成它的工作。我怎樣才能避免生成.stackdump
文件並在不正確的操作(如代碼中的一個)得到滿足時退出程序? P.S.我正在編制在Cygwin中的代碼用gcc和Boost.Python的嘗試/趕上,以避免.stackdump
有趣的是,它沒有的情況下,僅x[3]=2
工作,而是適用於所有其他情況:例如x[4]=2
或x[20]=2
,或者顯然,x[2]=2
。
#include <boost/python.hpp>
#include <iostream>
#include <iomanip>
using namespace std;
using namespace boost::python;
class Hello
{
std::string _msg;
public:
Hello(std::string msg){_msg = msg;}
void run(){
try{
double* x;
x = new double[3];
x[3] = 2.0;
delete [] x;
}catch(...){ exit(0); }
}
};
BOOST_PYTHON_MODULE(xyz)
{
class_<Hello>("Hello", init<std::string>())
.def("run",&Hello::run)
;
}
編輯:
根據什麼Maciek曾建議我嘗試以下竅門:
進行信號處理函數拋出一個異常,但不退出
void sig_action(int signo) {
std::cout << "SIGNAL " << signo << std::endl;
throw 1;
// exit(0);
}
現在嘗試在try/catch塊中放置一個可能有問題的函數(信號函數放在類構造函數中):
class Hello
{
std::string _msg;
public:
Hello(std::string msg){
_msg = msg;
signal(SIGABRT, sig_action);
signal(SIGSEGV, sig_action);
}
void set(std::string msg) { this->_msg = msg; }
std::string greet() { return _msg; }
void run(){
try{
double* x;
x = new double[3];
x[3] = 2.0;
delete [] x;
}catch(...){ cout<<"error in function run()\n"; exit(0); }
}
};
但是這樣一招行不通,因爲我希望它產生以下輸出:
SIGNAL 6
terminate called after throwing an instance of 'int'
SIGNAL 6
terminate called recursively
SIGNAL 6
terminate called recursively
....
(and many more times the same)
所以拋出異常,但它已被抓之前一切結束。有什麼辦法讓它在終止這個過程之前被抓到?
謝謝。事實上,這就是我如何找到一個錯誤 - 通過找到引發異常的代碼(很可能是內存訪問的一些問題)的一部分。我知道這不是應該如何找到一個錯誤,但它是我目前唯一的方式 - 它的一個長長的故事。我還添加了一些更正 - 似乎仍然拋出異常,但不是所有情況下;但在其中大部分。 – user938720 2013-03-24 21:07:35