Exception handling in C++

Exception handling in C++

An exception is a problem that occurs during the execution of a program. It disrupts the normal flow of the program. Exception Handling is a mechanism to handle the runtime errors so that flow of the program can be maintained. It transfers the control from one part of a program to another. Exception handling in C++ consist of three keywords: throw, try, catch. All exceptions are derived from std::exception class.

1. throw − Throws an exception when a problem arises.
2. try − Executes a code that can throw an exception.
3. catch − Handles exceptions of try block.

The try and catch blocks are a pair placed around the code that might create an exception. Code within a try/catch block is called as protected code. Syntax−

try
{
...
...
}
catch()
{
...
}

try block can also have multiple catch blocks for different exceptions. Also to handle all exceptions catch with three dots- catch(…) can be used. Exceptions can be thrown anywhere within a code block using throw statement.
Example-

#include <iostream>
using namespace std;
int main() {
  try {
    int a = 5;
    int b = 0;
    if (b == 0)
      throw (b);
    else
      cout << a / b;
  } catch (int n) {
    cout << "Divisor=" << n;
    cout << "\nError! Number cannot be divided by 0.";
  }
  return 0;
}

Output-

exception handling

Explanation-

In this example, 2 integers are a=5 and b=0. As we know any number divided by 0 is invalid and shows error in calculator. So inside the try block, condition is checked and if the number is 0 then it will throw an exception. The control jumps outside try block and executes the code inside catch block.

Program Parts-

1. #include is a pre-processor directive.
2. iostream is header file which has certain commands that c++ supports. E.g. return, main, etc.
3. .h is an extension for header file.
4. class is a keyword to create classes.
5. friend is a keyword to declare any function as a friend function.
6. int is data type. It indicates that the program returns a value.
7. main() is main function that indicates the compiler that the user written programs starts from here.
8. cout is the keyword use to print a message.
9. cin is the keyword use to store values in variables.
10. return statement is use to return a value. If any error occurs the program will return 0.

Conclusion-

So this was the concept of Exception handling in C++. We hope the concept was clear to you. If you have nay doubt regarding any of the concept or friend function do mention it in the comment section or mail us! For daily updates and more such content do follow us on Instagram.

Keep Programming!

ErrorFreeProgram.

1 COMMENT

Leave a Reply

Your email address will not be published. Required fields are marked *