Recall: An exn can depart of the recovery job, throw another exn(exception):
try {---}
catch(someError s) {
...
throw SomeOtherError {};
}
or rethrow the some exn:
try {---}
catch(someError s) {
...
throw;
}
<aside> đź’ˇ throw; vs throw s;
</aside>
A handller can act as a catch-all:
try {---} // ... : syntax of catch-all
catch(**...**) { // catches all exns
---
}
You can throw anything you want → don’t have to throw objects
When new fails: throw std::bad alloc
Never: Let a dtor throw or propagate an exn
- program wil abort immediately
- if you want a throwing dtor, you can tag it with noexecpt (false)
But - if a dtor throws during stack unwinding while dealing with another exn, you now have two active, unhandled exns, & the program will abort immediately
<aside> đź’ˇ Factory Method Pattern
Write a video game with 2 kinds of enermies: turtles + bullets
system randomly sends turtles & bullets, but bullets more freguent in harder levels
Two hierarchie
Never know exactly which ener comes next, so can’t call turtle/bullet ctors directly
I asked, put a factory method (that “creates things”) in Level that creates enermies.
class Level {
public: // ↓ factory method
virtual Enermy *createEnermy() = 0;
...
};
class Easy:public Level {
public:
Enermy *createEnermy() override {
// create morly turtles
};
class Hard:public Level {
public:
Enermy *createEnermy() override {
// create morly bullets
};
Level *l = new Easy;
Enermy *c = l->createEnermy();
</aside>
<aside> đź’ˇ Template Method Pattern
want subclasses to override superclass behaviour, but some aspects must stay the same. ex. There are red turtles and green turtles
class Turtle {
public:
void draw() {
draw Head();
draw Shell();
draw Feet();
}
private:
void drawHead() {...}
void drawFeet() {...}
virtual void drawShell() = 0;
};
class RedTurtle:public Turtle {
void drawShell() override {
// draw red shell
}
};
class GreenTurtle:public Turtle {
void drawShell() override {
// draw green shell
}
};
Subclasses can’t change the way a turtle B drawn (head, shell, feet) but can change the way the shell is drawn
Generalization: the Non-Virtual Interface (NVI) idiom
NVI says:
class DigitalMedia{
public:
virtual void play() = 0;
};
class DigitalMedia{
public:
void play() {
// checkCopyright()
doPlay();
// updatePlayCount()
}
private:
virtual void doPlay() = 0;
};
<aside> đź’ˇ Generalizes Template Method
<aside> đź’ˇ STL Maps - for creating dictionaries
eg. “arrays” that map strings to ints
import <map>
std::map<std::string, int> m;
m["abc"] = 2;
m["def"] = 3;
cout << m["ghi"] // 0
<< m["def"]; // 3
if key is not present, it is inserted & value is default constructed (for ints, 0)
</aside>