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?