Custom Exception in C++

Muhammad Husnain Oct 12, 2023
  1. Exception Handling in C++
  2. Custom Exception in C++
Custom Exception in C++

This brief programming tutorial is about implementing custom exception classes in C++ and fundamental rules to implement user-defined exception classes in C++.

Exception Handling in C++

In C++, exception handling is a method of dealing with runtime issues. We handle exceptions so the application’s usual flow may be maintained even when runtime issues occur.

In C++, an exception is an object thrown during the runtime process and disturbs the program’s normal execution.

The std::exception class is the root of all exceptions. If we don’t handle any exceptions, the application will print an error message and terminate.

Exceptions allow control to be passed from one program area to another. The three keywords try, catch, and throw handle exceptions in C++.

  1. throw - If a segment in your code can cause a problem, then we throw an exception using the throw keyword and specify the type of exception that can occur.
  2. try - It contains that code segment that can cause an error and needs to throw an exception.
  3. catch - the block called when an exception is thrown. In this block of code, we can inform the user about the error and end the program programmatically if required.

One common example of exceptions is the divide by zero error that occurs at runtime. It is the most frequently occurring exception in programs.

Let’s look at the following code snippet, which is prone to this divide by zero runtime exception.

#include <iostream>
using namespace std;
float divideFunc(int a, int b) {
  if (b == 0) {
    throw "User made a division with zero!";
  }
  return (a / b);
}
int main() {
  int num1 = 20;
  int num2 = 0;
  float result = 0;
  try {
    result = divideFunc(num1, num2);
    cout << result << endl;
  } catch (const char* msg) {
    cout << msg << endl;
  }
}

Output:

divide by zero runtime exception

Exception Class Hierarchy

The exception is a class with many classes as subclasses, and all these classes are the types of exceptions. C++ has a predefined set of common exception types for readily use in the programs.

Exception Class Hierarchy

Custom Exception in C++

Custom exceptions not specified in C++ may be beneficial to produce under specific circumstances. In C++, any type that meets certain criteria can be caught or thrown.

These include the type having a valid copy constructor and destructor.

Custom exceptions offer the exception handling mechanism with useful information about an issue. They may be created by either creating a new class with the necessary properties and throwing an instance of that class or by inheriting from std::exception and overriding the what() function.

Suppose we need to get the positive number input in our program. We can throw an exception if a negative number is entered.

We can make a custom exception class as follows.

class MyExceptionClass : public exception {
 public:
  const char* what() const throw() { return "Negative number not allowed\n"; }
};

This can be caught in the driver program as follows.

int main() {
  try {
    int a;
    cout << "Enter a number : \n";
    cin >> a;
    if (a < 0) {
      MyExceptionClass c;
      throw c;
    } else {
      cout << "you entered: " << a << endl;
    }
  } catch (exception& e) {
    cout << e.what();
  }
}

Output:

Exception output

We can see in the above code that we have inherited our custom exception class with the Exception class and override a method what() that will be called when the exception is thrown.

Muhammad Husnain avatar Muhammad Husnain avatar

Husnain is a professional Software Engineer and a researcher who loves to learn, build, write, and teach. Having worked various jobs in the IT industry, he especially enjoys finding ways to express complex ideas in simple ways through his content. In his free time, Husnain unwinds by thinking about tech fiction to solve problems around him.

LinkedIn

Related Article - C++ Exception