×

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined class types. Within the try block, we may write to throw an exception of type demo_exception class.

throw demo_exception();

Example:

#include <iostream>
#include <bits/stdc++.h>
#include <stdlib>
using namespace std; 
class demo_exception {
};


int main()
{	try {
		throw demo_exception();
	}
	catch (demo_exception d) {
		cout << "Caught exception of demo class \n";
	}
return 0;
}

OUTPUT:

Caught exception of demo_exception class
…………………………………………………………………
Process executed in 3213.33 seconds
Pres any key to continue.

Explanation:

We declared an empty class in the program. We toss an object of type demo class in the try block. The try block catches and shows the item.

Let's look at a basic user-defined exception example that uses the std::exception class to specify the exception.

#include <iostream>  
#include <exception> 
#include <bits/stdc++.h>
#include <stdlib> 
using namespace std;  
class My_exception : public exception{  
    public:  
        const char * what() const throw()  
        {  
            return "Attempted to divide by zero!\n";  
        }  
};  
int main()  
{  
    try  
    {  
        int i, j;  
        cout << "enter the two numbers : \n";  
        cin >> i >> j;  
        if (y == 0)  
        {  
            My_exception k;  
            throw k;  
        }  
        else  
        {  
            cout << "i / j = " << i/j << endl;  
        }  
    }  
    catch(exception& e)  
    {  
        cout << e.what();  
    }
return 0;  
}  

OUTPUT:

enter the two numbers :
50
5
x / y = 10  
……………………………………
Process executed in 121.2 seconds
Press any key to continue.

Explanation:

What() is a public function given by the exception class in the example above. It's used to find out what caused an exception.

Let us see an example of two-class program to implement exception handling:

#include <iostream>
#include <bits/stdc++.h>
#include <stdlib>
#include <exception>
using namespace std; 
class demo_exception1 {
};
class demo_exception2 {
};
int main()
{
	for (int i = 1; i <= 2; i++) {
		try {
			if (i == 1)
				throw demo_exception1();


			else if (i == 2)
				throw demo_exception2();
		}
		catch (demo_exception1 d1) {
			cout << "Caught exception of demo_exception1 class \n";
		}
		catch (demo_exception2 d2) {
			cout << "Caught exception of demo_exception2 class \n";
		}
	}
}

OUTPUT:

Caught exception of demo_exception1 class
Caught exception of demo_exception2 class
……………………………………………………………………
Process executed in 1112. Seconds
Press any key to continue.

Handling exceptions via inheritance

Exception handling can also be accomplished using inheritance. In the case of inheritance, the first catch block catches the object thrown by the derived class.

Example:

#include <iostream>
#include <bits/stdc++.h>
#include <stdlib>
#include <exception>
using namespace std; 
class demo_exception1 {
};
class demo_exception2 : public demo_exception1 {
};
int main()
{
	for (int a = 1; a <= 2; a++) {
		try {
			if (a == 1)
				throw demo_exeception1();


			else if (a == 2)
				throw demo_exception2();
		}
		catch (demo_exception1 d1) {
			cout << "Caught exception of demo_exception1 class \n";
		}
		catch (demo_exception2 d2) {
			cout << "Caught exception of demo_exception2 class \n";
		}
	}
}

OUTPUT:

Caught exception of demo_exception1 class
Caught exception of demo_exception1 class
…………………………………………………………………..
Process executed in 0.122 seconds 
Press any key to continue.

Explanation:

The program is similar to the last one, only demo_exception2 is now a derived class of demo_exception1. It's worth noting that the demo_exception1 catch block is written first. Demo_exception1 is the base class for demo_exception2, therefore any object thrown by demo_exception2 will be dealt with by the first catch block. As a result, the output is as indicated.

Constructor-based exception handling

Constructor-based exception handling is also possible. Although the function Object () { [native code] } cannot return any value, the try and catch block can.

Example:

#include <iostream>
#include <stdlib>
#include <bits/stdc++.h>
using namespace std; 
class demo_exception {
	int number; 
public:
	demo_exception(int i)
	{
	try {
		if (i == 0)
			// catch block would be called
			throw "Zero not allowed ";
			number = i;
			show();
		}
		catch (const char* exptn) {
			cout << "exception caught \n ";
			cout << exptn << endl;
		}
	}
	void show()
	{
		cout << "Number = " << number << endl;
	}
};
int main()
{
	// constructor will be called
	demo_exception(0);
	cout << "Again creating object \n";
	demo_exception(1);
}

OUTPUT:

exception caught
Zero not allowed
Again creating object
Number = 1
....................
Process executed in 0.342 seconds
Press any key to continue.

Explantion:

When i equal 0, an exception is raised and the catch block is invoked. When i = 1, no exception is thrown.

Let’s look at another example of user defined exception in C++ and try to visualize it:

#include <iostream>
#include <bits/stdc++.h>
#include <tsdlib>
using namespace std;
int main()
{
int i = -1;
try {
	cout << "Inside try \n";
	if (i < 0)
	{
		throw i;
		cout << "After throw \n";
	}
}
catch (int i ) {
	cout << "exception Caught \n";
}
cout << "After catch \n";
return 0;
}

OUTPUT:

Inside try
Exception Caught
After catch

Explanation:

Lines of the try block after the throw statement are not performed when an exception is thrown. The code after the catch block is run when an exception is captured. Catch blocks are usually written at the conclusion of a sentence.


Related Topics

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

4 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

C++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

Print Table Using While Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

Handling multiple clients on the Server with multithreading using Socket Programming in C or C++

To understand this guide completely, the reader is assumed to be familiar with the foundations of server and client models and socket programming. If one wants to create any scalable...

7 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.