Exception Handling in C++

In programming, it is normal for developers to commit mistakes that prompts unusual conditions called errors. All in all, these errors are of three kinds:

  1. Syntax Error
  2. Logical Error 
  3. Runtime Error

In this C++ Concept, you will learn:

What is Exception Handling in C++? 

Exception Handling in C++ gives you a method of taking care of surprising conditions like runtime errors. At whatever point a sudden situation happens, there is a movement of the program control to a unique function known as Handlers. 

To catch the exceptions, you place some segment of code under special case investigation. You put the part of the code inside the try-catch block. 

On the off chance that an uncommon circumstance happens inside that part of the code, an exception will be thrown. Then, the exception handler will assume control over the control of the program. 

On the off chance that no exception condition happens, the code will execute ordinarily. The handlers will be disregarded.

Why Exception Handling? 

Here are the reasons Why Exception Handling is used in C++:

You will isolate your error handling code from your ordinary code. The code will be more coherent and simpler to keep up. 

Functions can deal with the Exception they pick. Regardless of whether a function throws numerous exceptions, it will just deal with a few. The caller will deal with the uncaught exceptions. 

Basic Keywords in Exception Handling: 

Exception Handling in C++ falls around these three keywords: 

  • throw – when a program experiences an issue, it throws an Exception. The throw keyword assists the program by performing throw. 
  • catch – a program that utilises an exception handler to catch an Exception. It is added to the part of a program where you need to deal with the error.
  • try – the try block recognises the code block for which certain exceptions will be enacted. It ought to be followed by one/more catch blocks. 

Assume a code block will raise an exception. The exception will be gotten by a strategy utilising try and catch keywords. The try/catch block should encompass code that may throw an exception. Such code is known as protected code.

Syntax:

The try/catch takes this syntax:

try {
   // the protected code
} catch( Exception_Name exception1 ) {
   // catch block
} catch( Exception_Name exception2 ) {
   // catch block
} catch( Exception_Name exceptionN ) {
   // catch block
}	
  • Apart from the fact that we have one try statement, we can have many catch statement. 
  • The ‘ExceptionName’ is the name of the Exception for being caught. 
  • The exception1, exception2, exception3 and exceptionN are your defined names for referring to the exceptions.

Example 1:

#include<iostream>
#include<vector>
using namespace std;
	
int main() {
	vector<int> vec;
	vec.push_back(0);	
	vec.push_back(1);	
	// access the third element, that doesn't exist
	try
	{	
		vec.at(2);		
	}
	catch (exception&amp; ex)
	{
		cout << "Exception occurred!" << endl;
	}
	return 0;
}

Output:

Exception Occurred!

Screenshot of the above code:

Code Explanation: 

  • Include the ‘iostream’ header file in the program to utilise its functions. 
  • Include the ‘vector’ header file in the program to utilise its functions. 
  • Then include the ‘std namespace’ in the program to its classes without calling it. 
  • Call the main() function. The program logic ought to be added inside its body. 
  • Create a vector name vec to store integer data. 
  • Add component 0 to the vector named vec. 
  • Add component 1 to the vector named vec. 
  • Utilise the try statement to catch an exception. The { marks the start of the body try/catch block. The code added inside the body will turn into the protected code. 
  • Attempt to access the element stored in index 2 (third element) of the vector named vec. This component doesn’t exist. 
  • End of the body of the try/catch block. 
  • Catch the exception. The returned error message will be put away in the variable ex. 
  • Print out some message on the comfort if the exception is caught. 
  • End of the body of the catch block. 
  • The program should return a value upon fruitful execution. 
  • End of the main() function body.

Example 2:

#include <iostream>
using namespace std;
double zeroDivision(int x, int y) {
 
	if (y == 0) {
		throw "Division by Zero!";
	}
	return (x / y);
}
 
int main() {
	int a = 11;
	int b = 0;
	double c = 0;
 
	try {
		c = zeroDivision(a, b);
		cout << c << endl;
	}
	catch (const char* message) {
		cerr << message << endl;
	}
	return 0;
}

Output:

Division by Zero!

Screenshot of the above code:

Code Explanation: 

  • Include the ‘iostream’ header file in the program to utilise its functions. 
  • Include the ‘std namespace’ in the program to its classes without calling it. 
  • Create a function named ‘zeroDivision’ that takes two integer arguments, x and y. The function should return a double result. 
  • Utilise an if statement to check whether the estimation of variable argument y is 0. The ‘{‘ symbol marks the start of the ‘if’ body. 
  • A message to be returned/thrown if y is 0. 
  • End of the body of the ‘if’ statement. 
  • The zeroDivision function should return the value of ‘x/y’. 
  • End of the body of the ‘zeroDivision’ function. 
  • Call the main() method. The ‘{‘ marks the start of this method. 
  • Declare an integer variable a and allocating it the value 11. 
  • Declare an integer variable b and allocating it the value 0. 
  • And, declare a double variable c and allocating it the value 0. 
  • Utilise the try statement to catch an exemption. The ‘{‘ marks the start of the body of the try/catch block. The code added inside the body will turn into the protected code. 
  • Call the ‘zeroDivision’ function and passing to arguments a and b, that is, 11 and 0. The output of this operation will be stored in variable c. 
  • Print out the value of variable ‘c’ on the console. 
  • End of the body of the try/catch block. 
  • Catch the exception; The returned error message will be put away in the variable message. 
  • Print out the returned error message on the console. 
  • End of body of the catch block. 
  • The program should return a value upon fruitful execution. 
  • End of the main() function body.

C++ Standard Exceptions:






User-Defined Exceptions 

The C++ std::exception class permits us to define objects that can be thrown as exceptions. This class is defined in the <exception> header. The class gives us a virtual member function named what. 

This function returns an invalid ended character sequence of type char*. We can overwrite it in determined classes to have an exception depiction.

Rundown: 

  • With Exception Handling in C++, you can deal with runtime errors. 
  • Runtime errors are the errors that happen during program execution. 
  • Exception handling causes you to handle any startling conditions in your program. 
  • At the point when the startling situation happens, there is a movement of program control to handlers. 
  • To catch an exception, you place a part of the code under the try-catch block. 
  • The throw keyword helps the program to throw exceptions, assisting the program with taking care of the errors. 
  • The try keyword recognises the code block for which there is initiation of certain exceptions.
  • We can overwrite the ‘what() function’ of the exception header file to define our exceptions.

This brings us to the end of the blog on Exception Handling in C++. Hope this helps you to up-skill your C++ skills. To learn more about programming and other related concepts, check out the courses on Great Learning Academy

Also, if you are preparing for Interviews, check out these Interview Questions for C++ to ace it like a pro

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

sixteen + 3 =