-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexceptions.cpp
More file actions
79 lines (75 loc) · 1.8 KB
/
exceptions.cpp
File metadata and controls
79 lines (75 loc) · 1.8 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <memory>
#include <vector>
#include <random>
class Test
{
public:
Test() { std::cout << "Test():Acquire resources" << std::endl; }
~Test() { std::cout << "~Test():Release resources" << std::endl; }
};
void ProcessRecords(int count)
{
/*
Compare this code with the code that uses RAII.
*/
Test *t = new Test;
if (count < 10)
throw std::out_of_range("Count should be greater than 10");
int *p = new int[count];
int *pArray = (int *)malloc(count * sizeof(int));
if (pArray == nullptr)
{
throw std::runtime_error("Failed to allocate memory");
}
// Process the records
for (int i = 0; i < count; ++i)
{
pArray[i] = i;
}
// Unreachable code in case of an exception
free(pArray);
delete[] p;
delete t;
}
int main()
{
try
{
// ProcessRecords(std::numeric_limits<int>::max());
ProcessRecords(5);
}
catch (std::runtime_error &ex)
{
std::cout << ex.what() << std::endl;
}
catch (std::out_of_range &ex)
{
std::cout << ex.what() << std::endl;
}
catch (std::bad_alloc &ex)
{
std::cout << ex.what() << std::endl;
}
/*
std::exception is the base class for all standard
exception classes. It can be used as a handler if
the exception handling code is same for all child
class exception objects. This should be in the last
or it will catch the derived exceptions
*/
catch (std::exception &ex)
{
std::cout << ex.what() << std::endl;
}
/*
All-catch handler. Avoid as it does not give any
information about the exception, so it is difficult
to take any preventative action
*/
catch (...)
{
std::cout << "Exception" << std::endl;
}
return 0;
}