×

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

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

For Loop Examples in C++

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

6 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

How to Setup Environment for C++ Programming on Mac

Mac OS X code Installation There are so many environments available for C++. We are going to install jGrasp and Xcode in our mac operating system. Instruction for installation of jGrasp and...

2 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 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.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

How to Reverse a String in C++ using Do-While Loop

Strings In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string). The characters of...

4 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.