Eric
Eric

Reputation: 1243

Are exceptions in C++ only used to improve readability?

I am currently having a difficult time to grasp the purpose/use of exceptions in C++.

In other languages that im more familiar with like C# exceptions are automatically thrown if something goes wrong. For example a division by zero or an acess violation because you acessed a not assigned reference. What i used to do in those Languages, is to wrap sections of my code in try/catch blocks where it was possible for something horrible to happen. For example processing data that comes from a file that might be corrupted.

Now while diving a bit deeper into C++ i noticed both divisions by zero and segfaults don't generate exceptions:

#include<iostream>

void produceCrash()
{
    int i = 1/0; // program just crashes no exception

    int* p;
    *p = 10; // same thing here
}

int main()
{
    try
    {
        produceCrash();
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
    catch(...)
    {
        std::cerr << "Exception thrown!" << std::endl;
    }   

    return 0;
}

From what i understand, it is only possible to catch exceptions that got explicitly thrown by throw. That would mean any unexpected error simply can not be catched. Does this mean exceptions in C++ are simply an (cleaner and more readable) alternative for stuff like error code returning and just a way to control your program flow?

Upvotes: 1

Views: 160

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

Unfortunately there are two kinds of exceptions, that are easily confused by beginners:

The first is the language based exceptions, like you have with throw, try, catch and std::exception in C++.

The other kind are hardware exceptions, like what happens if you divide by zero or attempt to access a memory page not owned by your process.

C++ exceptions and hardware exceptions are separate and you can't use C++ exceptions to catch hardware exceptions. As you understand, you can only catch exceptions that are explicitly created by throw.

Many operating systems have ways to catch hardware exceptions though, for example signals could be used on POSIX systems (like for example SIGSEGV when attempting unallocated page access and similar). This makes it mostly operating-system dependent. But also note that many hardware exceptions are not possible to recover from, you can catch them but not really continue in any meaningful way anyway.

Upvotes: 3

Related Questions