File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -32,6 +32,7 @@ Examples include (and will expand to):
3232 * [ rot47] ( ./rot47/ )
3333* OOP
3434 * [ virtual-interface] ( ./virtual-interface/ )
35+ * [ oop-with-exception] ( ./oop-with-exception/ )
3536
3637---
3738
Original file line number Diff line number Diff line change 1+ # pull in shared compiler settings
2+ include ../common.mk
3+
4+ # per-example flags
5+ # CXXFLAGS += -pthread
6+
7+ # # get it from the folder name
8+ TARGET := $(notdir $(CURDIR ) )
9+ # # all *.cpp files in this folder
10+ SRCS := $(wildcard * .cpp)
11+ OBJS := $(SRCS:.cpp=.o )
12+
13+ all : $(TARGET )
14+
15+ $(TARGET ) : $(OBJS )
16+ $(CXX ) $(CXXFLAGS ) -o $@ $^
17+
18+ % .o : % .cpp
19+ $(CXX ) $(CXXFLAGS ) -c $< -o $@
20+
21+ run : $(TARGET )
22+ ./$(TARGET ) $(ARGS )
23+
24+ clean :
25+ rm -f $(OBJS ) $(TARGET )
26+
27+ # Delegates to top-level Makefile
28+ check-format :
29+ $(MAKE ) -f ../Makefile check-format DIR=$(CURDIR )
30+
31+ .PHONY : all clean run check-format
Original file line number Diff line number Diff line change 1+ /* *
2+ This example creates two classes A and B, where class B is a member of class A.
3+ And in the constructor of class A, it prints a message and throws an exception.
4+ So what would be the output?
5+
6+ B's constructor called.
7+ A's constructor called.
8+ B's destructor called.
9+ Caught exception: Exception in A's constructor
10+
11+ If an exception leaves a constructor, the object’s destructor does not run, because the object never finished
12+ construction. But destructors for already-constructed members/base-subobjects do run.
13+ */
14+
15+ #include < iostream>
16+ #include < stdexcept>
17+
18+ class B
19+ {
20+ public:
21+ B () { std::cout << " B's constructor called." << std::endl; }
22+ ~B () { std::cout << " B's destructor called." << std::endl; }
23+ };
24+
25+ class A
26+ {
27+ private:
28+ B b; // Member of class B
29+ public:
30+ A ()
31+ {
32+ std::cout << " A's constructor called." << std::endl;
33+ throw std::runtime_error (" Exception in A's constructor" );
34+ }
35+ ~A () { std::cout << " A's destructor called." << std::endl; }
36+ };
37+
38+ int
39+ main ()
40+ {
41+ try {
42+ A a; // Attempt to create an instance of A
43+ } catch (const std::exception& e) {
44+ std::cout << " Caught exception: " << e.what () << std::endl;
45+ }
46+ return 0 ;
47+ }
Original file line number Diff line number Diff line change 1+ #! /bin/bash
2+
3+ set -ex
4+
5+ ./oop-with-exception
You can’t perform that action at this time.
0 commit comments