Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Why Exception Handling?
3.
Exception Handling keywords
4.
Syntax 
4.1.
Code
5.
Example of exception handling
5.1.
Code
6.
Standard Exception in C++
7.
User-defined Exceptions
7.1.
Code
8.
Frequently asked questions
9.
Key Takeaways
Last Updated: Mar 27, 2024

What is an Exception Handling?

Author Shivam Verma
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction 

Before knowing exception handling, it is essential to know about exceptions. An exception is an unpredicted problem that arises during the program's execution. To deal with this unexpected problem, exception handling is used. Exception Handling is a mechanism to handle runtime errors. We perform exception handling to maintain the normal flow of the program even after the runtime errors.

Also see, Literals in C.Fibonacci Series in C++

Why Exception Handling?

The main advantages of exception handling over traditional error handling are given below.

  • To distinguish the error handling code from the normal code: 
    In traditional error handling, we always use if and else statements to handle the errors. These traditional error handling codes get mixed up with the normal code. This makes code less readable and maintainable. We use exception handling over traditional error handling to get rid of these problems.
  • A function can handle any exception they choose:
    In C++, a function can identify the exceptions that it throws with the help of the throw keyword. The caller of this function will handle the uncaught exception either by specifying it again or catching it.
  • Grouping of Error Types:
    We use exception handling to create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Exception Handling keywords

These are three keywords that are used to resolve exceptions in C++.

  • throw: when a problem arises in a program, it throws an exception. The throw keyword helps to throw the exception.
  • try: it represents a block of code that can throw an exception.
  • catch: it represents a block of code that is executed when a particular exception is thrown.   

Syntax 

Here is the syntax that takes try/catch.

Code

try
{
   // protected code
} 
catch(Exception_name exception_1)
{
   // catch block
} 
catch(Exception_name exception_2)
{
   // catch block
}
catch(Exception_name exception_N)
{
   // catch block
}

There is one try statement in the above syntax and many catch statements. The Exception_name is the name of the exception to be caught. The exception_1,exception_2, and exception_N are defined names. They are referring to the exceptions.

Example of exception handling

Code

#include<bits/stdc++.h>
using namespace std;
int main()
{
  try
  {
    int age=16;
    int voting_age=18;
    if (age>=voting_age)
    {
      cout<< "You are eligible for voting.";
    }
    else
    {
      throw "You are not eligible for voting.";
    }
  }
  catch (const char* msg)
  {
    cout<< "For voting, You must be at least 18 years old." <<endl;
    cout<<msg;  
  }
  return 0;
}

Output

For voting, You must be at least 18 years old.
You are not eligible for voting.

In the above example, the try block throws an exception when the age is less than 18. The catch block catches the exception.

Try and compile with online c++ compiler.

Standard Exception in C++

All the standard exceptions are defined in the <exception> class. These are described below:

Exception 

Description 

std::bad_exception It is used for handling unexpected exceptions in C++ programs.
std::exception An exception and parent class of all the standard exceptions of C++.
std::bad_alloc This exception occurs when the new operator fails to allocate the requested space.
std::domain_error This is an exception that is thrown when a mathematically invalid domain is used.
std::bad_typeid This is an exception thrown by typeid.
std::bad_cast This exception is thrown by dynamic_cast.
std::invalid_argument This is an exception thrown for using invalid arguments.
std::length_error This is an exception thrown after creating a big std::string.
std::out_of_range This exception is thrown by the 'at' method.
std::logic_error This is the type of exception that theoretically can be detected by reading the code.
std::overflow_error This is an exception that is thrown after the occurrence of a mathematical overflow.
std::range_error This is an exception that is thrown when you attempt to store an out-of-range value.
std::runtime_error This is the type of exception that cannot be detected via reading the code.
std::underflow_error This is an exception thrown after the occurrence of mathematical underflow.

 

User-defined Exceptions

Users can define their own exceptions by inheriting and overriding the exception class functionality. the given example shows how you can use std::exception class to implement your own exception in the standard way-

Code

#include<bits/stdc++.h>
#include<exception>
using namespace std;
class Divisor_zero_exception: public exception
{
    public:
        const char *what()const throw()
        {
            return "The divisor can not be zero.";
        }
};
int main()
{
    try
    {
        int a=15;
        int b=0;
        if (b == 0)
        {
            Divisor_zero_exception e;
            throw e;
        }
        else
        {
            cout<<"the value of a/b="<<a/b<<endl;
        }
    }
    catch(exception& ex)
    {
        cout << ex.what()<<endl;
    }
    return 0;
}

Output

The divisor can not be zero.

Frequently asked questions

  1. Which keyword is used to throw exceptions in C++?
    Ans: 'throw' keyword is used to throw exceptions in C++.
     
  2. Can we use try block without using the catch block?
    Ans: No, you can not use the 'try' block without the catch block. Using try block without using the catch block program will give a compilation error.
     
  3. Can a try block be nested under another try block?
    Ans: Yes, a try block can be nested under another try block.
     
  4. What are the benefits of Exception Handling?
    Ans: The benefits of exception handling are:
    1. Program is not terminated abruptly.
    2. Users will understand what errors are occurring in the program.

Key Takeaways

We learned what Exception Handling is in this blog. This blog also discussed the syntax, standard, and user-defined exceptions of C++.

This blog is over, but if you want to take your learnings to the next level, you can visit and read our other curated blogs by clicking here. Till then, have a nice day and Happy Coding! 

Recommended Reading:

Four Pillars of OOPS

Live masterclass