Exception Handling in C++: Try, Catch and Throw Keywords

Shailendra Chauhan  9 min read
11 Sep 2023
Beginner
893 Views

Exception Handling in C++: An Overview

Are you working with C++ and need help mastering exception handling? You've come to the right place! Dealing with errors, unexpected inputs, or other "exceptions" when programming can be a daunting task. However, exception handling in C++ makes it simpler, allowing your programs to run as efficiently and seamlessly as possible. In this blog post, we'll discuss how to use C++'s tools for exception handling. In order to increase your knowledge of C++ you can take a C++ online training. Let's get started by taking a closer look at what exceptions are and why they are important for the developer as well as for the user.

What is Exception Handling in C++?

In C++, exception handling indicates and deals with mistakes that may occur while a program is running, preventing unanticipated crashes. By providing error details, cutting down on development time, and improving user happiness, it facilitates troubleshooting. It's essential for developing a trustworthy and safe programming environment.

Exception Classes in C++

The structured error handling offered by C++'s exception classes makes it simpler to locate and fix problems. They provide specific information regarding problems, such as file names and line numbers. Exception classes make it easier to effectively address current and upcoming issues. All exception classes in C++ are descended from std::exception, with a few extras.

ExceptionDescription
std::exceptionIt is an exception as well as a parent class of all standard exceptions of C++.
std::logic_failureThis particular exception can be detected by reading any code.
std::runtime_errorThis exception cannot be detected by reading any code.
std::bad_exceptionThis exception is used to handle unexpected exceptions in a c++ program.
std::bad_castThis exception is generally thrown by dynamic_cast.
std::bad_typeidThis particular exception is generally thrown by typeid. 
std::bad_allocThis exception is generally thrown by new.

Keywords for Exception Handling in C++

Try

The try keyword assists in identifying the code block in which certain exceptions could be activated

Example

#include <iostream>
int main() {
 try {
 int result = 10 / 0; // This will throw a division by zero exception
 } catch (const std::exception& e) {
 std::cerr << "An error occurred: " << e.what() << std::endl;
 }
 return 0;
}

The division by zero exception that results from this C++ code's attempt to divide 10 by 0 is caught, and a message about the error is displayed to the standard error stream.

Output

An error occurred: std::exception

Catch

This particular program is used as an exception handler to catch any exception. This keyword is added to the section of any program where the developer needs to handle the problem

Example

#include <iostream>
#include <stdexcept>
int main() {
 try {
 int result = 10 / 0; // This will throw a division by zero exception
 } catch (const std::exception& error) {
 std::cerr << "An error occurred: " << error.what() << std::endl;
 }
 return 0;
}

Output

An error occurred: std::exception

This C++ code tries to divide 10 by 0, which causes a division by zero exception to occur. This exception is caught by the code, which then uses error.what() to print an error message that includes the exception's description before gracefully ending the program.

Throw

When any program finds a problem throw an exception. This keyword helps the program perform the throw feature.

Example

#include <iostream>
#include <stdexcept>
double divide(int a, int b) {
 if (b == 0) {
 throw std::runtime_error("Division by zero is not allowed");
 }
 return static_cast<double>(a) / b;
}
int main() {
 try {
 double result = divide(10, 0);
 std::cout << "Result: " << result << std::endl;
 } catch (const std::exception& error) {
 std::cerr << "An error occurred: " << error.what() << std::endl;
 }
 return 0;
}

This C++ code creates a function called divide that divides numbers and issues a std::runtime_error if it divides by zero. To ensure graceful error handling during division operations, it tries to divide 10 by 0 in the main function, catches the exception, and emits an error message that includes the exception's description.

Output

An error occurred: Division by zero is not allowed

Advantages of Exception Handling in C++

There are some advantages of exception handling in C++:

  • It helps to remove the error handling code from the main life of the code of that particular software
  • In the exception handling method, an exception has occurred in a function, that can be handled anywhere in the function calling stack
  • Any developer can choose certain ways to handle the exceptions and delegates other to callers' stack

FAQs

1. What is exception handling in C++?

Unexpected problems that occur while a program is running can be managed and recovered by using C++'s exception handling framework.

2. What is the main use of exception handling?

Exception handling is primarily used to gently manage errors, ensuring that programs can bounce back from unusual circumstances without crashing.

3. What are the keywords used in exception handling?

Try, catch, throw, finally, & throw() are all words that are used in exception handling.

4. What are the disadvantages of exception handling?

If exceptions are used excessively, disadvantages of exception handling may include increased code complexity as well as overhead.

5. What is the difference between checked and unchecked exceptions?

Unchecked exceptions (runtime exceptions) do not need to be explicitly handled; instead, they must be captured or expressly specified in the method signature for checked exceptions.

6. What are the five exception keywords?

Try, catch, throw, throw(), and catch(...) are the five exception keywords in C++ for catching all exceptions.

7. What is try catch and throw in C++?

In C++, the words throw and try are used to raise custom exceptions, catch is used to catch exceptions, and try is used to enclose code that could throw exceptions.

Summary

Unexpected errors that arise while a program is running can be handled with C++ exception handling. It recognizes and encrypts rare circumstances, enabling recovery. Fixing the problem that resulted in the exception and occasionally restarting the process are common recovery steps. This article includes try catch C++, throw an exception in C++, catch the exception in C++, and Try catch throw C++ Exception handling, you can learn more about exception handling in C++ with examples in C++ certification courses, providing a flexible mechanism for managing both anticipated and unanticipated errors. 

Share
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this