22
DecException Handling in C++: Try, Catch and Throw Keywords
Exception Handling in C++
Exception Handling in C++ deals with the techniques to deal with unwanted and unexpected events occurring during the program execution. When learning C++, one must be ready to deal with errors, unexpected inputs, or other exceptions
. However, exception handling
in C++ makes it simpler, allowing your programs to run efficiently.
In this blog post on C++ tutorials, we'll discuss how to use C++ tools for exception handling. We'll understand C++ exceptions, exception classes, try, catch, and throw keywords, etc. To increase your knowledge of C++, you can also take our online C++ Training.
Read More: Top 50 Mostly Asked C++ Interview Questions and Answers |
What is an Exception in C++?
Exceptions are runtime errors. Many a time, your program looks error-free during compilation. But, at the time of execution, some unexpected errors or events or objects come to the surface, and the program prints an error message and stops executing. Such unexpected happenings are calledexceptions
in C++.
Example
int a = 8/0;
In the above example, the program will show an error during runtime because dividing by zero is undefined.
What is Exception Handling in C++?
Exception handling in C++ is a technique to deal with exceptions
. It maintains your program flow despite runtime errors in the code and, thus, prevents unanticipated crashes. It facilitates troubleshooting by providing error details, cutting down on development time, and improving user happiness. It's essential for developing a trustworthy and safe programming environment.
What is an Exception Class in C++?
There are many standardsexceptions
in C++. All the standard exceptions are defined in the exception
Header file in C++. Thus, all the standard exception classes are derived from the std::exception
Class in C++.
Exception | Description |
| It is an exception as well as a parent class of all standard |
| This particular exception can be detected by reading any code. |
| This exception cannot be detected by reading any code. |
| This exception is used to handle unexpected exceptions in a C++ program. |
| This exception is generally thrown by |
| This particular exception is generally thrown by |
| This exception is generally thrown by |
Read More: C++ Interview Interview Questions and Answers
Keywords for Exception Handling in C++
try
: the block of code defined under this statement is being tested for runtime errors.throw
: throws anexception
when an error is detected. It is not necessary to use this keyword while usingstandard C++ exceptions
.catch
: specifies the code block to be executed if anexception
occurs in thetry
block.
Syntax
try {
// code to check exceptions
throw exception;
}
catch (exception) {
// code to handle exceptions
}
Every try
block is followed by the catch
Block. The throw
Statement throws an exception
, which is caught by the catch
block. The catch
block cannot be used without the try
block
Example in C++ Compiler
// program to divide two numbers and throw an exception if the divisor is 0
#include <iostream>
using namespace std;
int main() {
float numerator, denominator, result;
numerator = 9;
denominator = 0;
try {
// throw an exception if denominator is 0
if (denominator == 0)
throw 0; // Throwing an integer
result = numerator / denominator; // if denominator not zero
cout << numerator << " / " << denominator << " = " << result << endl;
}
catch (int exception) { // Catching an integer
cout << "Error: Cannot divide by " << exception << endl;
}
return 0;
}
- In the above code, we have put the
result = numerator / denominator
in thetry
block because this statement must not be executed if the denominator is 0. If the denominator is 0, the statements after thethrow
statement in thetry
block is skipped. - The
catch
block catches the thrown exception as its parameter and executes the statements inside it. - Here, the
exception
is of typeint
. Therefore, thecatch
statement accepts aint
parameter. - If there isn't any
exception
thrown, thecatch
block gets skipped.
Output
Error: Cannot divide by 0
- You can also use the throw keyword to output a reference number, like a custom error number/code for organizing purposes:
Example
#include <iostream> using namespace std; int main() { int numerator, denominator, result; numerator = 8; denominator = 0; try { // Throw an exception if the denominator is 0 if (denominator == 0) throw 505; // Throwing an integer result = numerator / denominator; // If the denominator is not zero cout << numerator << " / " << denominator << " = " << result << endl; } catch (int myNum) { // Catching an integer cout << "Error: Cannot divide by " << myNum << endl; } return 0; }
Output
Error: Cannot divide by 505
Handling All Types of Exceptions (...)
Suppose we do not know the types of exceptions that can occur in our try block or the throw type used in the try block; then, we can use the ellipsis symbol as our catch parameter. catch (...) is known as the catch-all exception handler.
Syntax
try {
// code to check exceptions
}
catch (...) {
// code to handle exceptions
}
Example
#include <iostream>
using namespace std;
int main() {
float numerator, denominator, result;
numerator = 9;
denominator = 0;
try {
// throw an exception if the denominator is 0
if (denominator == 0)
throw 0;
result = numerator / denominator; //if denominator not zero
cout << numerator << " / " << denominator << " = " << result << endl;
}
catch (...) {
cout << "Error: Cannot divide by " << endl;
}
return 0;
}
Output
Error: Cannot divide by
Multiple Catch Statements in C++ Exception Handling
This is like an if else-if ladder. Here, we can use multiple catch
statements for different kinds of exceptions
that can occur from a single block of code in the try
block.
Syntax
try {
// code to check exceptions
}
catch (exception1) {
// code to handle exception
}
catch (exception2) {
// code to handle exception
}
.
.
.
catch (...) {
// code code to handle exception
}
- Here, our program matches the type of exception that occurred in the
try
block with thecatch
statements. - If the
exception
that occurred matches any of the normalcatch
statements, that particularcatch
block gets executed. - If the exception occurred, it matches none of the normal
catch
statements, thecatch-all exception handler
,catch (...)
gets executed. - The
catch (...)
statement acts as the defaultcatch
statement. Therefore, it must always be the final block in thetry...catch
statement - It is not necessary to have a default
catch
block in the program.
Example in C++ Online Editor
#include <iostream>
using namespace std;
int main() {
float numerator, denominator, arr[] = {1, 2, 3, 4, 5};
int index;
cout << "Enter array index: ";
cin >> index;
try {
// throw exception if array is out of bounds
if (index >= sizeof(arr))
throw "Error: Array out of bounds!";
// not executed if array is out of bounds
cout << "Enter numerator: ";
cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;
// throw exception if denominator is 0
if (denominator == 0)
throw 0;
// not executed if denominator is 0
arr[index] = numerator / denominator;
cout << arr[index] << endl;
}
// catch "Array out of bounds" exception
catch (const char* msg) {
cout << msg << endl;
}
// catch "Divide by 0" exception
catch (float num) {
cout << "Error: Cannot divide by " << num << endl;
}
// catch any other exception
catch (...) {
cout << "Unexpected exception!" << endl;
}
return 0;
}
In the above code, we are dividing two numbers and storing their result in an array arr
at the index
value given by the user. There can be two possible exceptions here:
- Array index out of bounds: the indexvalue given by the user is greater than the size of the array
- Divide by 0: If the denominator is 0.
If there occurs any other exception in the try
block, it will be caught by the catch(...)
statement.
Output
- If the user enters a valid input.
Enter array index: 3 Enter numerator: 10 Enter denominator: 2 5
- If the user inputs an invalid index
Enter array index: 5 Error: Array out of bounds!
- If the denominator is 0
Enter array index: 2 Enter numerator: 8 Enter denominator: 0 Error: Cannot divide by 0
- If any unexpected exception occurs
Enter array index: 2 Enter numerator: "sScholarHat" // Entering a string instead of a number Unexpected exception!
You can also read: |
Summary
Unexpected errors that arise while a program is running can be handled with C++ exception handling. You can learn more about exception handling in C++ with examples in C++ courses, providing a flexible mechanism for managing both anticipated and unanticipated errors.