The try
block includes the code that might throw an exception, which means lead to some error. The catch
block then handles that exception, prevents the program from crashing, and allows it to continue running. In our example, the try-catch block is being used to handle the divide by zero error in our code.
If we didn't use the try-catch block, our program would terminate immediately when it encounters the division by zero error. But with the try-catch block, we're able to catch the exception and handle it gracefully by providing a meaningful error message to the user.
The throw
statement is used to throw an exception when you encounter an issue. The exception is thrown up to the nearest catch block. However, we will detail its usage later on.
Using try, throw, and catch is critical for building resilient software that handles different types of errors and exceptions, such as unexpected system failures, network errors, or invalid user input. For example, if you're working on a financial software that makes real-time trades, you wouldn't want your program to crash in the middle of a trade. With try, throw, and catch, you can handle such exceptions and prevent your system from crashing.
xxxxxxxxxx
using namespace std;
int main() {
try {
// Trying to divide by zero
int divisor = 0;
int result = 10 / divisor;
cout << "The division was successful.";
} catch (const exception& e) {
// Catch exception and print error message
cout << "An error occurred: " << e.what();
}
return 0;
}