Exception Handling is one of the advantages of C++ over C. Exceptions are run-time anomalies or anomalous conditions that occur during the execution of a program. 

There are two types of exceptions:

  1. Synchronous
  2. Asynchronous (Eg: disc failure)

For this reason, C++ provides the following specialized keywords.

try: denotes a block of code that has the potential to throw an exception.

catch: When an exception is thrown, catch denotes a block of code that is executed.

throw: Used to throw an exception to exception handler and keep track of the exceptions that a function raises but doesn't handle.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Why Do We Need to Handle Exceptions?

  • Exception handling is the process of handling errors and exceptions in such a way that they do not hinder the normal execution of the system.
  • Using exception handling, you can separate error-handling code from normal code, which makes code more readable and easier to maintain.

How to Use try-catch to Handle Exceptions in C++

When running C++ code, a variety of mistakes might occur, including programmer errors, mistakes caused by incorrect input, and other unforeseen events. When C++ encounters an error, it will usually halt and display an error message. 

try-catch c++ will throw an exception is the technical term for this (throw an error).

In C++, there are three keywords for managing exceptions: try, throw, and catch:

When a problem is found, the throw keyword raises an exception, allowing us to build a custom error.

An exception handler is used by a program to catch an exception. It's added to the area of a program where you'll be dealing with the issue. The catch keyword is used to accomplish this.

The try block identifies the code block for which exceptions will be triggered; one or more catch blocks should be placed after it.

The keywords try and catch come in pairs. Assume a code block throws an exception. A method employing try and catch keywords will catch the exception. 

try/catch Syntax

try {

//Code to try

throw exception; //Exception to throw if the code catches an error

}

catch() {

//Code that will run and handle errors

}

Example

#include<iostream>

#include<vector>

using namespace std;

int main() {

            vector<int> vec;

            vec.push_back(0);

            vec.push_back(1);

            // access the third element, which doesn't exist

            try

            {

                           vec.at(2);

            }

            catch (exception& ex)

            {

                           cout << "Exception occurred!" << endl;

            }

            return 0;

}

Output

try_catch_cpp_1.

Explanation

  • To use the functions of the iostream header file, include it in the program.
  • To use the vector header file's functions, include it in the program.
  • Without calling the std namespace, include it in the program's classes.
  • Use the main() method to get started. The logic of the program should be added to the body.
  • To hold integer values, create a vector named vec.
  • To the vector vec, add the 0th element.
  • To the vector labeled vec, add the element 1.
  • A remark. The C++ compiler will skip over it.
  • To catch an exception, use the try statement. This identifies the start of the body of the try/catch block. The code that is added to the body becomes the protected code.

Become a Certified UI UX Expert in Just 5 Months!

UMass Amherst UI UX BootcampExplore Program
Become a Certified UI UX Expert in Just 5 Months!

Example 

#include <iostream>

using namespace std;

double division by zero (int x, int y) {

         if (y == 0) {

                 throw “division done with the help of zero”

         }

         return (x / y);

}

int main() {

         int y = 15;

         int z = 0;

         double x = 0; 

         try {

                                 x = division by zero (y,z);

                                 cout << x << endl;

         }

         catch (const char* message) {

                                 cerr << message << endl;

         }

         return 0;

Output

try_catch_cpp_2

Explanation

  • To use the functions of the iostream header file, include it in the program.
  • Without calling the std namespace, include it in the program's classes.
  • Make a zeroDivision function that takes two integer arguments, x and y. The result of the function should be a double.
  • To see if the value of variable argument y is zero, use an if statement. This    indicates the start of the body.
  • If y is 0, the message will be returned/thrown.
  • The if statement's body has come to an end.
  • The x/y value should be returned by the zeroDivision function.
  • The zeroDivision function's body has come to an end.
  • Use the main() function to get started. This approach starts with the letter.

C++ Standard Exceptions

Returning a return code (also known as an error code) that the caller expressly tests via a conditional statement, such as if, is a typical alternative to try/catch/throw. Printf(), scanf(), and malloc(), for example, work in this way: the caller is expected to check the return value to determine if the function was successful.

Although the return code strategy is sometimes the most appropriate error management strategy, adding unneeded if statements have certain negative consequences:

  • Reduce time-to-market: Because conditional statements are branch points connected to the number of test cases required for white-box testing, adding unneeded conditional statements increases the amount of time spent testing. 

In other words, if you don't test every branch point, there will be instructions in your code that have never been run under test conditions until they are viewed by your users/customers. That's not good.

  • Increase the expense of development: Unnecessary control flow complexity makes detecting bugs, fixing bugs, and testing more difficult.

Exceptions allow programs to respond to unusual conditions (such as runtime errors) by delegating control to special routines known as handlers.

A section of code is put under exception inspection to capture exceptions. The function continues normally if no exception is thrown and all handlers are ignored.

The throw keyword is used inside the try block to throw an exception. The keyword catch, which must be used immediately after the try, is used to declare exception handlers.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

How to Handle Any Type of Exception

Exceptions allow programs to respond to unusual conditions (such as runtime errors) by delegating control to special routines known as handlers.

A section of code is put under exception inspection to capture exceptions. The function continues normally if no exception is thrown and all handlers are ignored. You can use the "three dots" syntax (...) inside the catch block if you do not know the throw type used in the try block, which will handle any type of exception. 

The throw keyword is used inside the try block to throw an exception. The keyword catch, which must be used immediately after the try, is used to declare exception handlers.

Example

// exceptions

#include <iostream>

using namespace std;

int main () {

  try

  {

    throw 40;

  }

  catch (int abc)

  {

    cout << "An exception occurred. Exception Nr. " << abc << '\n';

  }

  return 0;

}

Output

try_catch_cpp_3.

A throw expression takes one parameter (in this case, the integer value 20) and passes it to the exception handler as an input.

Syntax

The syntax for catch is similar to that of a conventional one-parameter function. This type of parameter is crucial because it is compared to the type of the argument supplied by the throw expression, and only if they match is the exception detected by that handler.

How to Use try-catch to Define User-Defined Exceptions

Dynamic exception specifications may exist in older code. In C++, they are now deprecated, though they are still supported. A throw specifier is appended to a dynamic exception specification that follows the declaration of a function. Consider the following scenario:

This declares a function named myfunction, which takes one char input and returns a double value. If this function throws an exception of a type other than int, instead of looking for a handler or calling std::terminate, it calls std::unexpected.

If this throw specifier is left empty with no type, any exception will be handled by std::unexpected.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion 

This was all about the try-catch function in c++ that you can use programming. These exceptions are used to handle the right type of complex problem to generate accurate results. 

If you are interested in learning more about exception handling in C++ and other concepts, you can enroll in Simplilearn’s Full Stack Web Development Program. With this course, you get to learn modern coding techniques and all aspects of Software Development using industry-relevant technologies with a Bootcamp-style rigor. You can also enroll in skill-up courses offered by Simplilearn and learn the most in-demand skills for free. All the courses in this program are focused on building strong foundational skills for career growth. Explore today!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449