Reputation: 3
I have one doubt regarding error handling...
If a function throws an exception and that exception isn't caught in main program will crash badly.
My question is why doesn't this program crash? If an exception is thrown from Test
function enterNumber
will throw an exception too even though it wasn't caught?
Shouldn't every function that might throw an exception be put in a try-catch block just in case it throws it?
1°
#include <iostream>
#include <stdexcept>
void Test(int number) {
if(number < 0)
throw std::domain_error("Number is negative");
}
int enterNumber() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
Test(number);
return number;
}
int main() {
try {
int number = enterNumber();
std::cout << "Entered number: " << number;
}
catch(std::domain_error e) {
std::cout << e.what();
}
return 0;
}
I thought it should be written like this:
2°
void Test(int number) {
if(number < 0)
throw std::domain_error("Number is negative");
}
int enterNumber() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
try {
Test(number);
}
catch(...) {
throw;
}
return number;
}
int main() {
try {
int number = enterNumber();
std::cout << "Entered number: " << number;
}
catch(std::domain_error e) {
std::cout << e.what();
}
return 0;
}
If someone could explain how the function enterNumber
throws an exception in case Test
throws it? (case 1°)
Thank you :)
Upvotes: 0
Views: 5209
Reputation:
You do not need to catch an exception from the function that called the function that caused the exception. Indeed, best practice is to catch the exception as far as possible (but no further) from the site where the exception was thrown, as it is only at higher levels of the program that you have sufficient information to produce meaningful error messages, and/or to deal with the exception in other ways. However, the exception should be caught at some level of the program, or the program will terminate in an uncontrolled manner.
Upvotes: 2