C++ exceptions:
You’re never supposed to divide by zero, so let’s use an example of throwing an exception when accidentally dividing by zero:
#include <iostream>
int main() {
float x = 0;
float y = 7;
try {
if (x == 0) {
throw “can’t divide by zero”;
} else {
std::cout << “y divided by x is: “;
std::cout << (y / x) << std::endl;
}
} catch(const char* ex) {
std::cout << “Failed because: “;
std::cout << ex << std::endl;
return 1; //error return value
}
return 0; //program completed with no errors
}
C++ doesn’t require you to do exception handling for things like division by zero, an array index being out of bounds, etc. Other languages require you to do so. But even if you’re not required, it’s good to do it anyway, or else you can end up with undefined behavior. C++ might not care, and it doesn’t force you to care, but you should do it anyway. C++ lets you do all kinds of bad stuff. For example, using uninitialized variables. Just because you can doesn’t mean you should. I’m more keen on languages that stop the developer from writing horrendous code, but C++ is ostensibly laissez-faire, for better or for worse (mostly for worse, in my opinion).
You can also make your own custom exceptions, as structs, and they must extend std::exception.
C++ cerr (error output):
Let’s use the above exception handling code, only this time with cerr instead of cout:
#include <iostream>
int main() {
float x = 0;
float y = 7;
try {
if (x == 0) {
throw “can’t divide by zero”;
} else {
std::cout << “y divided by x is: “;
std::cout << (y / x) << std::endl;
}
} catch(const char* ex) {
std::cerr << “Failed because: “;
std::cerr << ex << std::endl;
return 1; //error return value
}
return 0; //program completed with no errors
}
You could technically use cout for error messages, but that’s not what it’s intended for. cerr is specifically for error output.