Exception Handling in C++ | What is Exception Handling in C++

Exception handling in C++ is a special condition for developers to handle. In programming, it is normal to commit mistakes that prompt unusual conditions called errors. All in all, these errors are of three kinds:
- Syntax Error
- Logical Error
- Runtime Error
What is Exception Handling in C++?
Exception Handling in C++ is defined as a method that takes care of a surprising condition like runtime errors. At whatever point a sudden situation happens, there is a movement of the program control to a unique function known as Handlers.
To catch the exceptions, you place some code segment under special case investigation and that is kept inside a” try-catch ” block.
When an uncommon circumstance happens inside that part of the code, an exception will be thrown. Then, the exception handler will take control of the program.
When no exception condition happens, the code will execute ordinarily. The handlers will be disregarded.
A simple example to understand Exceptional handling in C++
#include <iostream>
int main() {
try {
// Code that may throw an exception
int numerator = 10;
int denominator = 0;
int result = numerator / denominator;
std::cout << "Result: " << result << std::endl;
}
catch (const std::exception& e) {
std::cout << "Exception occurred: " << e.what() << std::endl;
}
return 0;
}
In this example, the division operation numerator/denominator may throw a std::exception when the denominator is zero. The try block contains the code that might throw an exception, and the catch block catches the exception and handles it appropriately.
Also, now you can learn Exception Handling in C – A Free Online Course in Hindi
Why Exception Handling?
Here are the reasons why Exception Handling is used in C++:
- You will isolate your error handling code from your ordinary code. The code will be more coherent and simpler to keep up with.
- Functions can deal with the Exception they pick. Regardless of whether a function throws numerous exceptions, it will just deal with a few. The caller will deal with the uncaught exceptions.
Basic Keywords in Exception Handling:
Exception Handling in C++ falls around these three keywords:
What is try throw catch in c++?
Try throw catch in c++ is defined as:
- Throw – when a program experiences an issue, it throws an Exception. The throw keyword assists the program by performing a throw.
- Catch – a program that utilises an exception handler to catch an Exception. It is added to the part of a program where you must deal with the error.
- Try – the try block recognises the code block for which certain exceptions will be enacted. It ought to be followed by one/more catch blocks.
How try-catch in c++ works?
In C++, exception handling is done using the try-catch
mechanism. It allows you to catch and handle exceptions that occur during the execution of your program. The try
block contains the code that might throw an exception, and it handles the exception if it occurs. Here’s how it works:
- The code that might throw an exception is enclosed within a
try
block. If an exception occurs within this block, the execution of the code within thetry
block is immediately stopped, and the program looks for a matchingcatch
block to handle the exception. - After an exception is thrown, the program searches for a matching
catch
block. A matchingcatch
block is one that can handle the specific type of exception that was thrown. If a matchingcatch
block is found, the code within that block is executed. - If no matching
catch
block is found within the current scope, the program moves up the call stack, searching for an appropriatecatch
block in the calling functions. This process continues until a matchingcatch
block is found or until the program reaches the top level of the program (i.e.,main()
function). - Once a matching
catch
block is found, the code within that block is executed, and the program continues executing from the point immediately after thetry-catch
block.
Here’s an example to illustrate the usage of try-catch
:
#include <iostream>
int main() {
try {
// Code that might throw an exception
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
if (num2 == 0) {
throw std::runtime_error("Divide by zero exception");
}
int result = num1 / num2;
std::cout << "Result: " << result << std::endl;
}
catch (const std::exception& e) {
// Exception handling code
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Example1: Multiple Code Block
#include <iostream>
int main() {
try {
// Code that may throw an exception
int numerator = 10;
int denominator = 0;
int result = numerator / denominator;
std::cout << "Result: " << result << std::endl;
}
catch (const std::runtime_error& e) {
std::cout << "Runtime error occurred: " << e.what() << std::endl;
}
catch (const std::exception& e) {
std::cout << "Exception occurred: " << e.what() << std::endl;
}
return 0;
}
Here, we have added an additional catch
block to handle a specific type of exception, std::runtime_error
, before catching the more general std::exception
. The specific exception types should be caught before the more general ones.
Example2: Throwing a Custom Exception
#include <iostream>
#include <stdexcept>
void checkAge(int age) {
if (age < 0) {
throw std::invalid_argument("Age cannot be negative.");
}
else if (age < 18) {
throw std::out_of_range("You must be at least 18 years old.");
}
else {
std::cout << "Access granted." << std::endl;
}
}
int main() {
try {
int userAge = 15;
checkAge(userAge);
}
catch (const std::exception& e) {
std::cout << "Exception occurred: " << e.what() << std::endl;
}
return 0;
}
In this example, the checkAge
the function throws custom exceptions, std::invalid_argument
and std::out_of_range
, based on the age value provided. The try
block calls the checkAge
function, and if an exception is thrown, it is caught and handled in the catch
block.
How to use try-catch in c++?
Try-catch is an important keyword while performing exceptional conditions.
In the Try block, the “throw” keyword throws an exception when the code detects a problem, which lets us create a custom error.
Now “catch” keyword comes into a picture i.e. “catch” keyword allows you to define a block of code to be executed if an error occurs in the try block.
How do you catch exceptions in C++?
To catch exceptions, a part of the code is kept under inspection. This is done by closing that part of the code in a try-block. When an exceptional circumstance arises within that block, an exception is thrown and an exception handler takes control over the program.
How to throw an exception in c++?
Exception in c++ is thrown by using the “throw” keyword from inside the try-block. Exception handlers are declared with the “catch” keyword and must be placed immediately after the “try” block.
C++ Standard Exceptions
What is C++ Standard Exceptions?
C++ standard exceptions provide a list of standard exceptions defined in <exception> which we can use in our programs.
These exceptions are arranged in a parent-child class hierarchy:
User-Defined Exceptions
The C++ std::exception class permits us to define objects that can be thrown as exceptions. This class is defined in the <exception> header. The class gives us a virtual member function named what.
This function returns an invalid ended character sequence of type char*. We can overwrite it in determined classes to have an exception depiction.
This brings us to the end of the blog on Exception Handling in C++. Hope this helps you to up-skill your C++ skills. To learn more about programming and other related concepts, check out the courses on Great Learning Academy.
Also, if you are preparing for Interviews, check out these Interview Questions for C++ to ace it like a pro
Seize the opportunities that await you through our dynamic range of free courses. Whether you’re interested in Cybersecurity, Management, Cloud Computing, IT, or Software, we offer a broad spectrum of industry-specific domains. Gain the essential skills and expertise to thrive in your chosen field and unleash your full potential.