File tree 1 file changed +48
-1
lines changed
1 file changed +48
-1
lines changed Original file line number Diff line number Diff line change 1
- 1
1
+ #include < iostream>
2
+ #include < stdexcept>
3
+ #include < exception>
4
+ #include < string>
5
+ #include < fstream>
6
+
7
+ // prints the explanatory string of an exception. If the exception is nested,
8
+ // recurses to print the explanatory of the exception it holds
9
+ void print_exception (const std::exception & e, int level = 0 )
10
+ {
11
+ std::cerr << std::string (level, ' ' ) << " exception: " << e.what () << ' \n ' ;
12
+ try {
13
+ std::rethrow_if_nested (e);
14
+ } catch (const std::exception & e) {
15
+ print_exception (e, level+1 );
16
+ } catch (...) {}
17
+ }
18
+
19
+ // sample function that catches an exception and wraps it in a nested exception
20
+ void open_file (const std::string& s)
21
+ {
22
+ try {
23
+ std::ifstream file (s);
24
+ file.exceptions (std::ios_base::failbit);
25
+ } catch (...) {
26
+ std::throw_with_nested ( std::runtime_error (" Couldn't open " + s) );
27
+ }
28
+ }
29
+
30
+ // sample function that catches an exception and wraps it in a nested exception
31
+ void run ()
32
+ {
33
+ try {
34
+ open_file (" nonexistent.file" );
35
+ } catch (...) {
36
+ std::throw_with_nested ( std::runtime_error (" run() failed" ) );
37
+ }
38
+ }
39
+
40
+ // runs the sample function above and prints the caught exception
41
+ int main ()
42
+ {
43
+ try {
44
+ run ();
45
+ } catch (const std::exception & e) {
46
+ print_exception (e);
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments