-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExceptions.cpp
80 lines (66 loc) · 1.62 KB
/
Exceptions.cpp
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
80
#include <iostream>
#include <assert.h>
#include <exception>
// Compiler: Microsoft Visual C++ Compiler Nov 2012 CTP (v120_CTP_Nov2012)
using namespace std;
// Exception specifications
int OnlyIntExceptionsAllowed (int param) throw (int) {
//throw (float) 3.1415; // Would compile but cause exception.
return param;
}
float NoExceptionsAllowed (float param) throw() {
// throw 1; // Would compile but cause exception.
return param;
}
double AllExceptionsAllowed (double param) {
return param;
}
// Custom exception
class CustomException: public exception
{
virtual const char* what() const throw()
{
return "Custom Exception";
}
} CustomException;
int main () {
// Simple exceptions
try {
throw 1;
}
catch (int e) { // The type of the argument passed by the throw expression is checked against the exception.
cout << "An int exception occurred." << endl;
}
// Default catch
try {
throw "Error";
}
catch (int e) {
cout << "An int exception occurred." << endl;
}
catch (...) { // Will catch any type of exception.
cout << "An unknown exception occurred." << endl;
}
OnlyIntExceptionsAllowed(33);
NoExceptionsAllowed(11);
// Nesting Exceptions.
try {
try {
throw "Internal error.";
}
catch (int n) {
throw; // The internal catch block forwards the exception to the external level.
}
}
catch (...) {
cout << "Nested exception: " << endl;
}
// Custom exceptions
try {
throw CustomException;
}
catch (exception& e) { // Handler that catches exception objects by reference. Catches all classes derived from type exception.
cout << "Custom exception: " << e.what() << endl;
}
return 0;
}