In C++ programming, managing exceptions is achieved through try/catch constructs. The try block in C++ is where the code susceptible to exceptions is enclosed, while the catch block is employed to manage any exceptions that arise.
Syntax
It has the following syntax:
try {
//code block
throw exception;
}
catch (...){
//code block to handle errors
}
C++ Simple Try/Catch Example
Let's consider a scenario to demonstrate the try/catch mechanism in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //Main Function
{
try //try block
{
int n1 = 100, n2 = 0;
if (n2 == 0)
{
throw "Division by zero is not allowed!!";
// Throwing an exception.
}
std::cout << "Result: " << n1 / n2 << std::endl;
}
catch (const char* e) //catch block
{
// Catching the exception.
std::cout << "Exception caught: " << e << std::endl;
}
return 0;
}
Output:
Exception caught: Division by zero is not allowed!!
Explanation
In this instance, the try block endeavors to perform a division operation on n1 by n2. However, since n2 holds a value of zero, an exception is triggered, displaying the error message "Division by zero is not permitted!". Subsequently, the catch block manages this exception by presenting the error message, effectively averting a program crash.
Try Block
In C++, the try block serves the purpose of encapsulating code that might lead to runtime errors. Specifically, the try block houses code segments that have the potential to trigger runtime issues like division by zero, invalid memory access, or errors in file handling. Its functionality allows the program to execute risky operations with the assurance that any arising errors will be managed effectively and elegantly.
Catch Block
In C++, the catch clause follows the try block and is utilized to manage exceptions that arise within the try block. It defines the appropriate way to address specific types of errors, preventing abrupt program termination and enabling efficient handling of various exception scenarios.
- To manage exceptions effectively, the try and catch keywords are commonly employed together. The try block encloses the code that might trigger an error, while the catch block specifies how to manage that error if it occurs.
- Each try block in C++ must be accompanied by at least one catch block. The try block must precede the catch block to ensure that exceptions are handled correctly and do not lead to unforeseen program halts.
Handling All Exceptions with catch(...) in C++
In C++, when the specific type of exception is unknown, catch(...) can be employed to manage all exceptions. This approach guarantees that all exceptions, irrespective of their type, are appropriately identified and addressed.
Syntax
It has the following syntax:
try
{
// Code that may cause an exception
}
catch (...)
{
// Code to handle any type of exception
}
C++ Example of Handling all Exception using Catch
Let's examine a C++ illustration demonstrating the handling of all exceptions using a catch block.
Example
#include <iostream>
using namespace std;
int main()
{
float dividend =100, divisor = 0, quotient;
try
{
if (divisor == 0)
throw "Division by zero error!";
quotient = dividend / divisor;
cout << dividend << " / " << divisor << " = " << quotient << endl;
}
catch (...)
{
cout << "Error: Division cannot be performed due to a wrong divisor." << endl;
}
return 0;
}
Output:
ERROR!
Error: Division cannot be performed due to a wrong divisor.
Explanation
In this illustration, we aim to separate the dividend by the divisor while managing any potential exceptions. Within the try block, it verifies whether the divisor is zero and raises an exception in such a scenario; if not, the division operation is carried out. The catch block functions as a universal handler, capturing any exceptions and presenting an error message in case of an incorrect division.
C++ Exception Handling Using Multiple Catch Blocks
In C++, multiple catch blocks can be utilized following a try block to manage various exception types. In case of an unfamiliar exception, the catch(...) block will address it.
Syntax
It has the following syntax:
try {
// Code section that may throw several types of errors
}
catch (int e) {
// It handles int exception
}
catch (double e) {
// It handles double exception
}
catch (const char* e) {
// It handles the string literal exception
}
C++ Exception Handling Example using Multiple Catch Block
Let's explore a C++ illustration demonstrating exception handling with the utilization of several catch blocks.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
float n, deno, a[] = {1, 2, 3, 4, 5};
int i;
cout << "Enter the index: ";
cin >> i;
try
{
if (i < 0 || i >= sizeof(a) / sizeof(a[0]))
throw "Error: Array index out of bounds!!";
cout << "Enter the numerator: ";
cin >> n;
cout << "Enter the denominator: ";
cin >> deno;
if (deno == 0)
throw 0;
a[i] = n / deno;
cout << "Result: " << a[i] << endl;
}
catch (const char* err)
{
cout << err << endl;
}
catch (int)
{
cout << "Error: Cannot divide by zero!" << endl;
}
catch (...)
{
cout << "Unexpected error occurred!" << endl;
}
return 0;
}
Output:
Enter the index: 3
Enter the numerator: 6
Enter the denominator: 0
ERROR!
Error: Cannot divide by zero!
Explanation
This C++ software divides numbers and saves outcomes in an array, handling exceptions through multiple catch blocks. Initially, it validates if the index from the user falls within the acceptable range; if not, it triggers an exception. In case the denominator is zero, it raises another exception, and the last catch block deals with any unexpected errors, guaranteeing effective error management.
Try/Catch in Functions
In C++, functions have the ability to throw exceptions that can be caught in main or other calling functions. Utilizing try-catch blocks within functions allows for proper exception handling. If a function throws an exception, the program will search for the closest catch statement to manage it.
C++ Example of Try/Catch in Functions
Let's consider a C++ instance to demonstrate the implementation of try-catch within a function.
Example
#include <iostream>
using namespace std; //using standard namespace
void divide(int x, int y) {
if (y == 0)
throw "Division by zero Exception!";
cout << "The Division Result is: " << x / y << endl;
}
int main() { //Main Function
try {
divide(15, 0);
}
catch (const char* msg) {
cout << "Caught exception: " << msg << endl;
}
return 0;
}
Output:
Caught exception: Division by zero Exception!
Explanation
In this instance, the divide(int x, int y) function executes the division operation. Within the main function, the divide function is called within a try block. When attempting to divide by zero (divide(15, 0)), the function generates an exception, which is then caught by the catch block designed to manage const char* exceptions.
Nested Try/Catch Blocks
In C++, nested try-catch statements can be declared within either a try block or a catch block. This feature enables the handling of exceptions in scenarios where distinct exceptions occur in various parts of the code.
Syntax
It has the following syntax:
try {
//code section of the outer try block
try
{
//code section of the inner try block
catch (...)
{
//inner catch block
}
}
catch (...)
{
//outer catch block
}
C++ Nested try/catch block Example
Let's consider a scenario to demonstrate the concept of a Nested try/catch block in the C++ programming language.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() { //Main Function
try {
cout << "Outer try block started" << endl;
try {
cout << "Inner try block started" << endl;
int x = 15, y = 0;
if (y == 0)
throw "Division by zero in the inner block!";
cout << "The Division Result is: " << x / y << endl;
}
catch (const char* message) {
cout << "Caught in the inner catch: " << message << endl;
throw; // Rethrow the exception to outer catch
}
cout << "It would not be executed if exception is rethrown." << endl;
}
catch (const char* message) {
cout << "Caught in the outer catch: " << message << endl;
}
cout << "It continues after nested try-catch..." << endl;
return 0;
}
Output:
Outer try block started
Inner try block started
Caught in inner catch: Division by zero in inner block!
Caught in outer catch: Division by zero in inner block!
It continues after nested try-catch...
Explanation
In this illustration, we showcase nested try-catch blocks where an error related to dividing by zero is initially captured within the inner catch block and subsequently thrown again to be managed by the outer catch block. This demonstrates the flow of control when exceptions are transferred within nested sections.
C++ Try/Catch MCQs
1) Which of the following keywords is used to specify that a function will throw any exceptions in C++?
- throwall
- throw
- throws
- throwexception
2) Which of the following options is used to implement the Exception Handling in C++?
- Using try-catch block
- Using Error Handling Schedules
- Using Exception Keyword
- Using Exception block
3) What happens if no exception is thrown in a try block?
- The catch block is executed
- The program crashes
- An Exception is thrown by default
- The catch block is skipped
4) Which of the following options is an exception in C++?
- Semicolon not written
- Variable not declared
- Division by zero
- An expression is wrongly written
5) Is it possible to utilize a catch block in C++ without a corresponding try block?
- This is permissible solely within function scopes
- However, it can solely be used with standard exceptions