---------------
void taskmaster()
{
    try{
        auto result = do_task();
        // uycie wyniku
    }
    catch (Some_error) {
        // niepowodzenie zadania do_task: rozwizanie problemu
    }
}

int do_task()
{
    // ...
    if (/* Zadanie zostao wykonane */)
        return result;
    else
        throw Some_error{};
}
---------------
struct Range_error {};
void f(int n)
{
    if (n<0 || max<n) throw Range_error {};
    //...
}
---------------
void fnd(Tree*p, const string& s)
{
    if (s == p->str) throw p; // znaleziono s
    if (p->left) fnd(p->left,s);
    if (p->right) fnd(p->right,s);
}

Tree*find(Tree* p, const string& s)
{
    try{
        fnd(p,s);
    }
    catch (Tree* q) { // q->str==s
        return q;
    }
    return 0;
}
---------------
void callC() // wywoanie funkcji z C++; zamiana errno na throw
{
    errno = 0;
    c_function();
    if (errno) {
        //... lokalne porzdki w razie potrzeby i moliwoci...
        throw C_blewit(errno);
    }
}

extern "C" void call_from_C() noexcept // wywoanie funkcji C++ z C; zamiana throw na errno
{
    try {
        c_plus_plus_function();
    }
    catch (...) {
        //... lokalne porzdki w razie potrzeby i moliwoci...
        errno = E_CPLPLFCTBLEWIT;
    }
}
---------------
void f()
{
    string buf;
    cin>>buf;
    //...
    g(1);
    h(buf);
}
---------------
bool g(int);
bool h(const char*);
char*read_long_string();

bool f()
{
    char*s = read_long_string();
    //...
    if (g(1)) {
        if (h(s)) {
            free(s);
            return true;
        }
        else {
            free(s);
            return false;
        }
    }
    else {
        free(s);
        return false;
    }
}
---------------
void g(int) noexcept;
void h(const string&) noexcept;
---------------
namespace Points { // (vx[i],vy[i]) jest punktem dla wszystkich i
    vector<int> vx;
    vector<int> vy;
};
---------------
void f(int i)
{
    int* p = new int[10];
    //...
    if (i<0) {
        delete[] p; // usunicie przed zgoszeniem wyjtku i powstaniem wycieku
        throw Bad();
    }
    //...
}
---------------
void use_file(const char* fn) // naiwny kod
{
    FILE* f = fopen(fn,"r");

    // ... uycie f...

    fclose(f);
}
---------------
void use_file(const char* fn) // niezgrabny kod
{
    FILE* f = fopen(fn,"r");
    try{
        //... uycie f...
    }
    catch (...) { // przechwycenie wszystkich moliwych wyjtkw
        fclose(f);
        throw;
    }
    fclose(f);
}
---------------
void acquire()
{
    // zajcie zasobu 1
    //...
    // zajcie zasobu n

    //... uycie zasobw...

    // zwolnienie zasobu n
    //...
    // zwolnienie zasobu 1
}
---------------
class File_ptr {
    FILE*p;
public:
    File_ptr(const char* n, const char* a)  // otwarcie pliku n
        : p{fopen(n,a)}
    {
        if (p==nullptr) throw runtime_error{"File_ptr: nie mona otworzy pliku"};
    }

    File_ptr(const string& n, const char*a) // otwarcie pliku n
        :File_ptr{n.c_str(),a}
    {}

    explicit File_ptr(FILE* pp)             // przyjcie zaoenia dot. wasnoci pp
        :p{pp}
    {
        if (p==nullptr) throw runtime_error("File_ptr: nullptr"};
    }

    //... odpowiednie operacje przenoszenia i kopiowania...

    ~File_ptr() { fclose(p); }

    operator FILE*() { return p; }
};
---------------
void use_file(const char*fn)
{
    File_ptr f(fn,"r");
    //... uycie f...
}
---------------
class Locked_file_handle {
    File_ptr p;
    unique_lock<mutex> lck;
public:
    X(const char* file , mutex& m)
        : p{file ,"rw"}, // zajcie file
        lck{m}           // zajcie m
    {}
    //...
};
---------------
template<typename F>
struct Final_action {
    Final_action(F f): clean{f} {}
    ~Final_action() { clean(); }
    F clean;
};
---------------
template<class F>
Final_action<F> finally(F f)
{
    return Final_action<F>(f);
}
---------------
void test()
    // wykonuje niezdyscyplinowane zajmowanie zasobw
    // demonstruje, e moliwe s przypadkowe dziaania
{
    int* p = new int{7};                       // pewnie powinien zosta uyty unique_ptr (5.2)
    int* buf = (int*)malloc(100*siz eof(int)); // alokacja w stylu C

    auto act1 = finally([&]{ delete p;
                             free(buf);        // dezalokacja w stylu C
                             cout<< "egnaj, okrutny wiecie!\n";
                         }
                    );
    int var = 0;
    cout << "var = " << var << '\n';

    // zagniedony blok:
    {
        var=1;
        auto act2 = finally([&]{ cout<< "W kocu!\n"; var=7; });
        cout << "var = " << var << '\n';
    }// tu jest wywoywana act2

    cout << "var = " << var << '\n';
} // tu jest wywoywana act1
---------------
var=0
var=1
W kocu!
var=7
egnaj, okrutny wiecie!
---------------
void f(int n)
    // n powinien by w przedziale <1,max)
{
    if (2<debug_level && (n<=0 || max<n)
        throw Assert_error("Problem zakresu");
    //...
}
---------------
namespace Assert {
    enum class Mode { throw_, terminate_, ignore_ };
    constexpr Mode current_mode = CURRENT_MODE;
    constexpr int current_level = CURRENT_LEVEL;
    constexpr int default_level = 1;

    constexpr bool level(int n)
        { return n<=current_level; }

    struct Error : runtime_error {
        Error(const string& p) :runtime_error(p) {}
    };

    // ...
}
---------------
namespace Assert {
    //...

    string compose(const char* file , int line, const string& message)
        // skada wiadomo z nazwy pliku i numeru wiersza
    {
        ostringstream os ("(");
        os << file << "," << line << "):" << message;
        return os.str();
    }

    template<bool condition =level(default_level), class Except = Error>
    void dynamic(bool assertion, const string& message ="Assert::dynamic - niepowodzenie")
    {
        if (assertion)
            return;
        if (current_mode == Assert_mode::throw_)
            throw Except{message};
        if (current_mode == Assert_mode::terminate_)
            std::terminate();
    }

    template<>
    void dynamic<false ,Error>(bool, const string&) // nic nie rb
    {
    }

    void dynamic(bool b, const string& s) // domylne dziaanie
    {
        dynamic<true,Error>(b,s);
    }

    void dynamic(bool b)                 // domylna wiadomo
    {
        dynamic<true,Error>(b);
    }
}
---------------
void f(int n)
    // n powinien by w przedziale <1,max)
{
    Assert::dynamic<Assert::level(2),Assert::Error>(
        (n<=0 || max<n), Assert::compose(__FILE__,__LINE__,"Problem z zakresem");
    //...
}
---------------
void f(int n)
    // n powinien by w przedziale <1,max)
{
    Assert::dynamic((n<=0 || max<n),Assert::compose(__FILE__,__LINE__,"Problem z zakresem");
    //...
}
---------------
void f(int n)
    // n powinien by w przedziale <1,max)
{
    dynamic(n<=0||max<n);
    //...
}
---------------
class No_copy {
    No_copy(const No_copy&) = delete; // zabronienie kopiowania (17.6.4)
};

class My_error {
    //...
};

void f(int n)
{
    switch (n) {
    case 0: throw My_error{}; // OK
    case 1: throw No_copy{};  // bd: nie mona kopiowa No_copy
    case 2: throw My_error;   // bd: My_error jest typem, a nie obiektem
    }
}
---------------
void f()
{
    string name {"Byron"};
    try{
        string s = "in";
        g();
    }
    catch (My_error) {
        //...
    }
}

void g()
{
    string s = "excess";
    {
        string s = "or";
        h();
    }
}

void h()
{
    string s = "not";
    throw My_error{};
    string s2 = "at all";
}
---------------
struct Some_error { };

void fct()
{
    //...
    if (something_wrong)
        throw Some_error{};
}
---------------
struct My_error2 : std::runtime_error {
    const char* what() const noexcept { return "My_error2"; }
};
---------------
void g(int n) // zgasza wyjtek
{
    if (n)
        throw std::runtime_error{"Poddaj si!"};
    else
        throw My_error2{};
}

void f(int n) // sprawdza, jaki wyjtek zgasza funkcja g()
{
    try{
        void g(n);
    }
    catch (std::exception& e) {
        cerr << e.what() << '\n';
    }
}
---------------
double compute(double) noexcept; // nie moe zgasza wyjtkw
---------------
double compute(double x) noexcept;
{
    string s = "Kasia i Ania";
    vector<double> tmp(10);
    //...
}
---------------
template<typename T>
void my_fct(T& x) noexcept(Is_pod<T>());
---------------
template<typename T>
void call_f(vector<T>& v) noexcept(noexcept(f(v[0]))
{
    for (auto x : v)
        f(x);
}
---------------
template<class T, siz e_t N>
void swap(T (&a)[N], T (&b)[N]) noexcept(noexcept(swap(*a,*b)));
---------------
void f(int) throw(Bad,Worse); // moe zgasza tylko wyjtki Bad i Worse
void g(int) throw();          // nie moe zgasza wyjtkw
---------------
void f()
{
    try{
        throw E{};
    }
    catch(H) {
        // kiedy tu dotrzemy?
    }
}
---------------
void g()
{
    int x1;

    try{
        int x2 = x1;
        //...
    }
    catch (Error) {
        ++x1; // OK
        ++x2; // bd: x2 nie jest w zakresie
        int x3 = 7;
        //...
    }
    catch(...) {
        ++x3; // bd: x3 nie jest w zakresie
        //...
    }

    ++x1;     // OK
    ++x2;     // bd: x2 nie jest w zakresie
    ++x3;     // bd: x2 nie jest w zakresie
}
---------------
void h()
{
    try{
        //... Kod mogcy zgosi wyjtek...
    }
    catch (std::exception& err) {
        if (can_handle_it_completely) {
            // ... obsuga wyjtku...
            return;
        }
        else {
            //... zrobienie co si da...
            throw; // ponowne zgoszenie wyjtku
        }
    }
}
---------------
void m()
{
    try{
        // ... jakie dziaania...
    }
    catch (std::exception& err) { // obsuguje wszystkie typy wyjtkw z biblioteki standardowej
        // ... porzdkowanie...
        throw;
    }
}
---------------
void m()
{
    try{
        //... co...
    }
    catch (...) { // obsuguje wszystkie wyjtki
        // ... porzdkowanie...
        throw;
    }
}
---------------
void f()
{
    try{
        // ...
    }
    catch (std::ios_base::failure) {
        //... obsuguje bdy strumienia iostream (30.4.1.1)...
    }
    catch (std::exception& e) {
        //... obsuguje bdy biblioteki standardowej (30.4.1.1)...
    }
    catch (...) {
        //... obsuguje wszystkie pozostae bdy (13.5.2.2)...
    }
}
---------------
void g()
{
    try{
        //...
    }
    catch (...) {
        //... obsuguje wszystkie wyjtki (13.5.2.2)...
    }
    catch (std::exception& e) {
        //... obsuguje wyjtki biblioteki standardowej (30.4.1.1)...
    }
    catch (std::bad_cast) {
        //... obsuguje bd zwizany z rzutowaniem dynamic_cast (22.2.1)...
    }
}
---------------
int main()
try
{
    //... jakie dziaania...
}
catch (...} {
    //... obsuga wyjtku...
}
---------------
class X {
    vector<int> vi;
    vector<string> vs;

    //...
public:
    X(int,int);
    //...
};

X::X(int sz1, int sz2)
tr y
    :vi(sz1), // konstrukcja vi z sz1 wartoci typu int
    vs(sz2),  // konstrukcja vs z sz2 acuchw
{
    //...
}
catch (std::exception& err) { // tu s przechwytywane wyjtki zgaszane dla vi i vs
    //...
}
---------------
using terminate_handler = void(*)(); // z nagwka <exception>

[[noreturn]] void my_handler()       // procedura obsugi zamknicia programu nie moe zwraca wartoci
{
    // okrelony sposb zamknicia programu
}

void dangerous() // bardzo niebezpieczne!
{
    terminate_handler old = set_terminate(my_handler);
    //...
    set_terminate(old); // przywrcenie starej procedury obsugi zamknicia programu
}
---------------
int main()
try{
    //...
}
catch (const My_error& err) {
    //... obsuga bdu...
}
catch (const std::range_error&)
{
    cerr << "Bd zakresu: znowu!\n";
}
catch (const std::bad_alloc&)
{
    cerr << "Brak pamici dla operatora new\n";
}
catch (...) {
    //...
}
---------------
try{
    // ... jakie instrukcje...
}
catch(...) {
    prom.set_exception(current_exception());
}
---------------
template<class T, class A = allocator<T>>
class vector {
private:
    T* elem;  // pocztek alokacji
    T* space; // koniec sekwencji elementw, pocztek przestrzeni alokowanej dla ewentualnego rozszerzania
    T* last;  // koniec alokowanej przestrzeni
    A alloc;  // alokator
public:
    using size_type = unsigned int;          // typ do okrelania rozmiaru wektora

    explicit vector(size_type n, const T& val = T(), const A& = A());

    vector(const vector& a);                 // konstruktor kopiujcy
    vector& operator=(const vector& a);      // przypisanie kopiujce

    vector(vector&& a);                      // konstruktor przenoszcy
    vector& operator=(vector&& a);           // przypisanie przenoszce

    ~vector();

    size_type siz e() const { return space-elem; }
    size_type capacity() const { return last-elem; }
    void reserve(size_type n);                // zwiksza pojemno do n

    void resize(siz e_type n, const T& = {}); // zwiksza rozmiar do n
    void push_back(const T&);                 // dodaje element na kocu
    //...
};
---------------
template<class T, class A>
vector<T,A>::vector(size_type n, const T& val, const A& a) // ostrzeenie: naiwna implementacja
    :alloc{a}                 // alokator kopiujcy
{
    elem = alloc.allocate(n); // pobranie pamici dla elementw (34.4)
    space = last = elem+n;
    for (T*p = elem; p!=last; ++p)
        a.construct(p,val);   // tworzenie kopii val w *p (34.4)
}
---------------
template<class T, class A>
vector<T,A>::vector(size_type n, const T& val, const A& a) // bardziej dopracowana implementacja
    :alloc{a}                 // alokator kopiujcy
{
    elem = alloc.allocate(n); // pobranie pamici dla elementw

    iterator p;

    try{
        iterator end = elem+n;
        for (p=elem; p!=end; ++p)
            alloc.construct(p,val); // utworzenie elementu (34.4)
        last = space = p;
    }
    catch (...) {
        for (iterator q = elem; q!=p; ++q)
            alloc.destroy(q);       // usuwanie utworzonych elementw
        alloc.deallocate(elem,n);   // zwolnienie pamici
        throw;                      // ponowne zgoszenie wyjtku
    }
}
---------------
template<class For, class T>
void uninitialized_fill(For beg, For end, const T& x)
{
    For p;
    try{
        for (p=beg; p!=end; ++p)
            ::new(static_cast<void*>(&*p)) T(x); // tworzenie kopii x w *p (11.2.4)
    }
    catch (...) {
        for (For q = beg; q!=p; ++q)
             (&*q)->~T();                       // usunicie elementu (11.2.4)
        throw;                                  // ponowne zgoszenie wyjtku (13.5.2.1)
    }
}
---------------
template<class T, class A>
vector<T,A>::vector(size_type n, const T& val, const A& a) // nadal troch niechlujne
    :alloc(a)                                // alokator kopiujcy
{
    elem = alloc.allocate(n);                // pobranie pamici dla elementw
    try{
        uninitialized_fill(elem,elem+n,val); // kopiowanie elementw
        space = last = elem+n;
    }
    catch (...) {
        alloc.deallocate(elem,n);            // zwolnienie pamici
        throw;                               // ponowne zgoszenie wyjtku
    }
}
---------------
template<class T, class A = allocator<T> >
    struct vector_base { // struktura pamici dla wektora
    A alloc; // alokator
    T*elem;  // pocztek alokacji
    T*space; // koniec sekwencji elementw, pocztek przestrzeni alokowanej dla ewentualnego rozszerzania
    T*last;  // koniec alokowanej przestrzeni

    vector_base(const A& a, typename A::size_type n)
        : alloc{a}, elem{alloc.allocate(n)}, space{elem+n}, last{elem+n} { }
    ~vector_base() { alloc.deallocate(elem,last-elem); }

    vector_base(const vector_base&) = delete; // adnych operacji kopiowania
    vector_base& operator=(const vector_base&) = delete;

    vector_base(vector_base&&);               // operacje przenoszenia
    vector_base& operator=(vector_base&&);
};
---------------
template<class T, class A>
vector_base<T,A>::vector_base(vector_base&& a)
    : alloc{a.alloc},
    elem{a.elem},
    space{a.space},
    last{a.space}
{
    a.elem = a.space = a.last = nullptr; // nie posiada ju adnej pamici
}

template<class T, class A>
vector_base<T,A>::& vector_base<T,A>::operator=(vector_base&& a)
{
    swap(*this,a);
    return *this;
}
---------------
template<class T, class A = allocator<T> >
class vector {
    vector_base<T,A> vb;                // dane s tutaj
    void destroy_elements();
public:
    using size_type = unsigned int;

    explicit vector(size_type n, const T& val = T(), const A& = A());

    vector(const vector& a);            // konstruktor kopiujcy
    vector& operator=(const vector& a); // przypisanie kopiujce

    vector(vector&& a);                 // konstruktor przenoszcy
    vector& operator=(vector&& a);      // przypisanie przenoszce

    ~vector() { destroy_elements(); }

    size_type size() const { return vb.space-vb.elem; }
    size_type capacity() const { return vb.last-vb.elem; }

    void reserve(size_type);            // zwiksza pojemno

    void resize(size_type , T = {});    // zmienia liczb elementw
    void clear() { resize(0); }         // oprnia wektor
    void push_back(const T&);           // dodaje element na kocu

    //...
};

template<class T, class A>
void vector<T,A>::destroy_elements()
{
    for (T*p = vb.elem; p!=vb.space; ++p)
        p->~T(); // usuwa element (17.2.4)
    vb.space=vb.elem;
}
---------------
template<class T, class A>
vector<T,A>::vector(size_type n, const T& val, const A& a)
    :vb{a,n} // alokuje przestrze dla n elementw
{
    uninitialized_fill(vb.elem,vb.elem+n,val); // tworzy n kopii val
}
---------------
template<class T, class A>
vector<T,A>::vector(const vector<T,A>& a)
   :vb{a.alloc,a.size()}
{
    uninitialized_copy(a.begin(),a.end(),vb.elem);
}
---------------
template<class T, class A>
vector<T,A>::vector(vector&& a) // konstruktor przenoszcy
    :vb{move(a.vb)}             // przeniesienie wasnoci
{
}
---------------
template<class T, class A>
vector<T,A>::& vector<T,A>::operator=(vector&& a) // przypisanie przenoszce
{
    clear();       // usuwa elementy
    swap(*this,a); // przenosi wasno
}
---------------
template<class T, class A>
vector<T,A>& vector<T,A>::operator=(const vector& a) // oferuje siln gwarancj (13.2)
{
    vector_base<T,A> b(alloc,a.size());           // pobiera pami
    uninitialized_copy(a.begin(),a.end(),b.elem); // kopiuje elementy
    destroy_elements();                           // usuwa stare elementy
    swap(vb,b);                                   // przekazuje wasno
    return*this;                                  // niejawnie usuwa star warto
}
---------------
template<class T, class A>
vector<T,A>& vector<T,A>::operator=(const vector& a) // zapewnia siln gwarancj (13.2)
{
    vector temp {a};       // alokator kopiujcy
    std::swap(*this,temp); // zamienia reprezentacje
    return *this;
}
---------------
template<class T, class A>
vector<T,A>& vector<T,A>::operator=(const vector& a)       // wersja zoptymalizowana, tylko 
                                                           // z podstawow gwarancj (13.2)
{
    if (capacity() < a.size()) { // alokuje reprezentacj nowego wektora:
        vector temp {a};         // alokator kopiujcy
        swap(*this,temp);        // zamienia reprezentacje
        return*this;             // niejawnie usuwa star warto
    }

    if (this == &a) return*this; // optymalizacja autoprzypisania

    size_type sz = size();
    size_type asz = a.size();
    vb.alloc = a.vb.alloc;       // alokator kopiujcy
    if (asz<=sz) {
        copy(a.begin(),a.begin()+asz,vb.elem);
        for (T*p = vb.elem+asz; p!=vb.space; ++p)          // usuwa nadmiarowe elementy (16.2.6)
            p->~T();
    }
    else {
        copy(a.begin(),a.begin()+sz,vb.elem);
        uninitialized_copy(a.begin()+sz,a.end(),vb.space); // tworzy dodatkowe elementy
    }
    vb.space = vb.elem+asz;
    return*this;
}
---------------
template<class T, class A>
void safe_assign(vector<T,A>& a, const vector<T,A>& b) // proste a = b
{
    vector<T,A> temp{b}; // kopiuje elementy b do obiektu tymczasowego
    swap(a,temp);
}
---------------
template<class T, class A>
void safe_assign(vector<T,A>& a, vector<T,A> b) // proste a = b (uwaga: b jest przekazywany przez warto)
{
    swap(a,b);
}
---------------
template<class T, class A>
void vector<T,A>::reserve(size_type newalloc) // pierwsza, niedoskonaa prba
{
if (newalloc<=capacity()) return; // obszar alokacji nie moe by zmniejszony
vector<T,A> v(capacity());        // tworzy wektor o nowej pojemnoci
copy(elem,elem+size(),v.begin())  // kopiuje elementy
swap(*this,v);                    // instaluje now warto
} // niejawnie zwalnia star warto
---------------
template<class T, class A>
void vector<T,A>::reserve(size_type newalloc)
{
    if (newalloc<=capacity()) return;            // obszar alokacji nie moe by zmniejszony
    vector_base<T,A> b {vb.alloc,newalloc};      // zajcie nowej przestrzeni
    uninitialized_move(elem,elem+size(),b.elem); // przeniesienie elementw
    swap(vb,b);                                  // instalacja nowej bazy
} // niejawnie zwalnia star przestrze
---------------
template<typename In, typename Out>
Out uninitialized_move(In b, In e, Out oo)
{
    for (; b!=e; ++b,++oo) {
        new(static_cast<void*>(&*oo)) T{move(*b)}; // konstrukcja z przenoszeniem
        b->~T();                                   // usuwanie
    }
    return b;
}
---------------
template<class T, class A>
void vector<T,A>::resize(size_type newsize , const T& val)
{
    reserve(newsize);
    if (size()<newsize)
        uninitialized_fill(elem+size(),elem+newsize ,val); // tworzy nowe elementy: <size(),newsize)
    else
        destroy(elem.size(),elem+newsize);    // usuwa niepotrzebne elementy: <newsize,size())
    vb.space = vb.last = vb.elem+newsize;
}
---------------
template<typename In>
void destroy(In b, In e)
{
    for (; b!=e; ++b) // usuwa <b,e)
        b->~T();
}
---------------
template<class T, class A>
void vector<T,A>::push_back(const T& x)
{
    if (capacity()==size())                   // brak wolnej przestrzeni; realokacja
        reserve(sz?2*sz:8);                   // zwikszenie lub rozpoczcie od 8
    vb.alloc.construct(&vb.elem[size()],val); // dodaje val na kocu
    ++vb.space;                               // zwiksza rozmiar
}