skillup-logo

Full Stack Development for Beginners

  • Full Stack Development for Beginners

    Full Stack Development for Beginners

    Certificate of completion

    It’s 100% Free

prevNext

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.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

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.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

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.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors