代码片段(3)[全屏查看所有代码]
1. [代码]1. 在异常对象构造函数中生成一个堆栈跟踪
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
// Sample Program:
// Compiler: gcc 3.2.3 20030502
// Linux: Red Hat
#include <execinfo.h>
#include <signal.h>
#include <exception>
#include <iostream>
using
namespace
std;
/
class
ExceptionTracer
{
public
:
ExceptionTracer()
{
void
* array[25];
int
nSize = backtrace(array, 25);
char
** symbols = backtrace_symbols(array, nSize);
for
(
int
i = 0; i < nSize; i++)
{
cout << symbols[i] << endl;
}
free
(symbols);
}
};
|
2. [代码]2. 将信号转换成异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
template
<
class
SignalExceptionClass>
class
SignalTranslator
{
private
:
class
SingleTonTranslator
{
public
:
SingleTonTranslator()
{
signal
(SignalExceptionClass::GetSignalNumber(), SignalHandler);
}
static
void
SignalHandler(
int
)
{
throw
SignalExceptionClass();
}
};
public
:
SignalTranslator()
{
static
SingleTonTranslator s_objTranslator;
}
};
// An example for SIGSEGV
class
SegmentationFault :
public
ExceptionTracer,
public
exception
{
public
:
static
int
GetSignalNumber() {
return
SIGSEGV;}
};
SignalTranslator<SegmentationFault> g_objSegmentationFaultTranslator;
// An example for SIGFPE
class
FloatingPointException :
public
ExceptionTracer,
public
exception
{
public
:
static
int
GetSignalNumber() {
return
SIGFPE;}
};
SignalTranslator<FloatingPointException> g_objFloatingPointExceptionTranslator;
|
3. [代码]3. 处理构造函数中的异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
class
ExceptionHandler
{
private
:
class
SingleTonHandler
{
public
:
SingleTonHandler()
{
set_terminate(Handler);
}
static
void
Handler()
{
// Exception from construction/destruction of global variables
try
{
// re-throw
throw
;
}
catch
(SegmentationFault &)
{
cout <<
"SegmentationFault"
<< endl;
}
catch
(FloatingPointException &)
{
cout <<
"FloatingPointException"
<< endl;
}
catch
(...)
{
cout <<
"Unknown Exception"
<< endl;
}
//if this is a thread performing some core activity
abort
();
// else if this is a thread used to service requests
// pthread_exit();
}
};
public
:
ExceptionHandler()
{
static
SingleTonHandler s_objHandler;
}
};
//
class
A
{
public
:
A()
{
//int i = 0, j = 1/i;
*(
int
*)0 = 0;
}
};
// Before defining any global variable, we define a dummy instance
// of ExceptionHandler object to make sure that
// ExceptionHandler::SingleTonHandler::SingleTonHandler() is invoked
ExceptionHandler g_objExceptionHandler;
A g_a;
//
int
main(
int
argc,
char
* argv[])
{
return
0;
}
|