How to Throw an Exception in C++?
In C++, exception handling is a mechanism that allows us to handle runtime errors and exceptions are objects that represent an error that occurs during the execution of a program. In this article, we will learn how to throw an exception in C++.
Throw a C++ Exception
Throwing an exception means sending the exception to the catch block after it has occurred in the program. To throw an exception in C++, we can use the throw
keyword followed by an instance of the exception. When a program encounters a throw statement, then it immediately terminates the current function and starts finding a matching catch block to handle the thrown exception. Generally throw
is used inside a try
block or a function that is called within a try
block.
Syntax to Throw an Exception in C++
throw exception_object
Here, exception_object
is typically an instance of an exception class that can be a built-in type (like int
or const char*
), but more commonly, we use a class derived from std::exception
.
C++ Program to Throw an Exception
The following program illustrates how we can throw an exception in case of divide by zero runtime error in C++.
// C++ Program to illustrate how to throw an exception
#include <iostream>
#include <stdexcept>
using namespace std;
// Function to perform division
void divide(int x, int y)
{
// Check if the denominator is zero
if (y == 0) {
// If denominator is zero, throw an exception of
// type runtime_error
throw runtime_error("Division by zero error");
}
// If denominator is not zero, perform division and
// print Result
cout << "Result: " << x / y << endl;
}
int main()
{
try {
divide(10, 0);
}
catch (const exception& e) {
// Catch any exception thrown during the execution
// of divide function
cerr << "Exception caught: " << e.what() << endl;
}
return 0;
}
Output
Exception caught: Division by zero error
Time Complexity: O(1)
Auxiliary Space: O(1)