🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Error handling: try, catch and your own exception class

Throw and catch exceptions for cases such as an invalid resistance, an out-of-range ADC value or text that cannot be converted to a number; get to know the standard exception classes, write your own exception class and see how RAII cleans up when an error occurs.

So far we have dealt with error cases in two ways: either we checked at the start of a function and left with return 1;, or we returned a bool and hoped the caller would check it. That is enough for small programs. But in a deep call chain, for example main → olcumAl → sicaklikOku → adcOku, the error code from the bottom has to be carried up by hand at every level; if one level forgets, the error disappears silently. We saw another problem in the classes lesson: a constructor has no return value, so how would the call Direnc(-5) report the error? C++'s answer is exceptions: an exception is thrown where the error occurs, caught at the first place that can handle it, and every function in between is left automatically.

throw, try and catch

#include <iostream>
#include <stdexcept>

double akim(double volt, double direnc) {
    if (direnc <= 0.0) {
        throw std::invalid_argument("direnc pozitif olmali");
    }
    return volt / direnc;
}

int main() {
    try {
        double i1 = akim(12.0, 4.0);
        std::cout << "I1 = " << i1 << " A\n";
        double i2 = akim(12.0, 0.0);          // burada firlatilir
        std::cout << "I2 = " << i2 << " A\n"; // bu satir calismaz
    } catch (const std::invalid_argument& e) {
        std::cout << "Hata: " << e.what() << '\n';
    }
    std::cout << "Program devam ediyor\n";
    return 0;
}
I1 = 3 A
Hata: direnc pozitif olmali
Program devam ediyor

throw creates an exception object and throws it, and the function is left at that moment; the line return volt / direnc; is never reached. The program goes up the call chain looking for the first try block that catches an exception of this type. When it finds one, the rest of the try block is skipped, the matching catch block runs, and the program continues from the line after the catch. e.what() returns the message we gave the exception.

Notice that we stored the result in a separate variable before printing it. Had we written std::cout << "I2 = " << akim(12.0, 0.0), C++17's left-to-right evaluation rule would have printed "I2 = " before the exception, leaving a half-finished line.

If no catch catches the exception, the program ends with std::terminate. In other words, an exception cannot be ignored; that is its biggest advantage over error codes, which can be forgotten.

Standard exception classes

The standard library provides ready-made exception classes in the <stdexcept> header. They are all derived from std::exception, so catch (const std::exception& e) catches all of them.

ClassWhen?
std::invalid_argumentThe argument makes no sense: a negative resistance, text that is not a number
std::out_of_rangeOut of bounds: an invalid index for vector::at, a number beyond the type's limits
std::runtime_errorErrors you can only detect while running: the sensor did not answer, the file is corrupt
std::bad_allocnew could not allocate memory (header <new>)

Besides your own code, some standard library functions throw exceptions too. std::stod, which converts text to a number, and at(), which you saw in the arrays lesson, are among them:

#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

int main() {
    std::vector<double> olcum = {22.5, 23.0, 21.5};
    try {
        std::cout << olcum.at(5) << '\n';
    } catch (const std::out_of_range&) {
        std::cout << "Sinir disi erisim yakalandi\n";
    }

    std::vector<std::string> girdiler = {"230.5", "abc", "1e999"};
    for (const auto& g : girdiler) {
        try {
            double v = std::stod(g);
            std::cout << g << " -> " << v << '\n';
        } catch (const std::invalid_argument&) {
            std::cout << g << " -> sayi degil\n";
        } catch (const std::out_of_range&) {
            std::cout << g << " -> double sinirini asiyor\n";
        }
    }
    return 0;
}
Sinir disi erisim yakalandi
230.5 -> 230.5
abc -> sayi degil
1e999 -> double sinirini asiyor

You can put several catch blocks after one try; the first one that fits runs. If you will not use the exception object, you can leave out its name: catch (const std::out_of_range&). The what() messages of the standard classes differ from compiler to compiler, so here we printed our own text ("out-of-bounds access caught", "not a number", "exceeds the double range").

Your own exception class and cleanup with RAII

If you also want to report which sensor channel failed, you write your own exception class. This uses derivation (inheritance) from an existing class: the line class SensorHatasi : public std::runtime_error means "SensorHatasi is a runtime_error, it has everything a runtime_error has and adds its own fields on top". We have not covered inheritance in detail; using this pattern is enough here.

#include <iostream>
#include <stdexcept>
#include <string>

class SensorHatasi : public std::runtime_error {
public:
    SensorHatasi(int kanal, const std::string& mesaj)
        : std::runtime_error(mesaj), kanal_(kanal) {}
    int kanal() const { return kanal_; }

private:
    int kanal_;
};

class OlcumOturumu {                  // RAII: yikici her durumda calisir
public:
    OlcumOturumu() { std::cout << "Oturum acildi\n"; }
    ~OlcumOturumu() { std::cout << "Oturum kapandi\n"; }
};

double sicaklikOku(int kanal, int ham) {
    if (ham < 0 || ham > 1023) {
        throw SensorHatasi(kanal, "ADC degeri aralik disi: " + std::to_string(ham));
    }
    return ham * 330.0 / 1023;        // LM35, 3.3 V referans, 10 mV/C
}

void olcumAl() {
    OlcumOturumu oturum;
    double t1 = sicaklikOku(1, 76);
    std::cout << "K1: " << t1 << " C\n";
    double t2 = sicaklikOku(2, 1100);     // firlatir
    std::cout << "K2: " << t2 << " C\n";  // calismaz
}

int main() {
    try {
        olcumAl();
    } catch (const SensorHatasi& e) {
        std::cout << "Kanal " << e.kanal() << ": " << e.what() << '\n';
    } catch (const std::exception& e) {
        std::cout << "Genel hata: " << e.what() << '\n';
    }
    return 0;
}
Oturum acildi
K1: 24.5161 C
Oturum kapandi
Kanal 2: ADC degeri aralik disi: 1100

Look at the order of the output: the "Oturum kapandi" (session closed) line came before the catch block. As the exception left olcumAl, the function's local objects were destroyed one by one and the destructor of oturum ran. This is called stack unwinding. In the memory management lesson we saw that RAII cleans up "even on an early return"; the same guarantee holds for exceptions. Files, ports, smart pointers: they all close by themselves when an error occurs.

The order of the catch blocks matters too. The specific one (SensorHatasi) comes first, then the general one (std::exception). If you reverse them, the general block catches everything and the specific block never runs.

Embedded systems note: In many microcontroller projects exceptions are switched off entirely with a compiler flag (-fno-exceptions); the reasons are the extra code size and an unwinding step whose duration cannot be predicted. In those projects errors are reported with return values or with C++17's std::optional type. In desktop and server software, exceptions are the standard way.

Common mistakes

  • Catching an exception by value. catch (std::exception e) copies the derived object into the base class and cuts off the extra information (slicing). Always catch by const reference: catch (const std::exception& e).
  • Writing the general catch before the specific one. Since the first matching block runs, the specific block becomes dead code. Compilers often warn about this.
  • Throwing from a destructor. Destructors run during unwinding; if a second exception appears at that moment, the program ends with std::terminate. Destructors are treated as noexcept by default; if an error happens inside one, log it but do not throw.

Exercise

Make the Direnc class robust. The constructor takes the value and the maximum power; if the value is zero or negative, it throws std::invalid_argument. The guc(volt) method computes the power with V * V / R; if the power exceeds the maximum, it throws AsiriYukHatasi (overload error), which you derive from std::runtime_error. In main, try three quarter-watt (0.25 W) resistors of 100, -5 and 22 ohms at 5 V. Try each resistor in its own try block so that the others are still tried when one fails.

Hint: in an exception class with no extra fields you do not need to write the constructor again: if you write using std::runtime_error::runtime_error; inside the class, the base class constructors are inherited. Put the try/catch inside the loop.

Solution

#include <iostream>
#include <stdexcept>
#include <vector>

class AsiriYukHatasi : public std::runtime_error {
public:
    using std::runtime_error::runtime_error;    // yapicilari devral
};

class Direnc {
public:
    Direnc(double ohm, double maksGuc) : ohm_(ohm), maksGuc_(maksGuc) {
        if (ohm <= 0.0) {
            throw std::invalid_argument("gecersiz direnc degeri");
        }
    }
    double guc(double volt) const {
        double p = volt * volt / ohm_;
        if (p > maksGuc_) {
            throw AsiriYukHatasi("guc siniri asildi");
        }
        return p;
    }

private:
    double ohm_;
    double maksGuc_;
};

int main() {
    std::vector<double> degerler = {100.0, -5.0, 22.0};
    for (double r : degerler) {
        try {
            Direnc d(r, 0.25);                  // ceyrek watt direnc
            double p = d.guc(5.0);
            std::cout << r << " ohm: " << p << " W\n";
        } catch (const AsiriYukHatasi& e) {
            std::cout << r << " ohm: " << e.what() << '\n';
        } catch (const std::invalid_argument& e) {
            std::cout << r << " ohm: " << e.what() << '\n';
        }
    }
    return 0;
}
100 ohm: 0.25 W
-5 ohm: gecersiz direnc degeri
22 ohm: guc siniri asildi

At 100 Ω the power came out at exactly 25 / 100 = 0.25 W; it did not exceed the limit, so it was accepted (in a real design you would leave a twofold margin instead of running a resistor at its limit). At 22 Ω the power rose to about 1.14 W and exceeded the limit. The -5 Ω object was never created, because if a constructor throws, the object counts as never having been created.

In short, exceptions carry an error safely from where it occurs to where it can be handled, and RAII makes sure no resource is left open along the way. In the next and final lesson we will write sensor data to files and read it back, handling broken lines with exactly this technique.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. What happens when throw runs inside a function?
2. SensorHatasi is a class derived from std::runtime_error. Which of the following catch orders is correct?
3. Why is the form catch (const std::exception& e) recommended when catching exceptions?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.