Custom exceptions in c++

Custom exceptions in c++

In the C++ programming language, custom exceptions are implemented in C++ programs to handle or manage runtime custom user-defined error exception messages at program execution time without crashing or damaging the user-created C++ program. As we have previously discussed, several standard exception classes in C++ (such as std::runtime_error and std::invalid_argument) exist. C++ programmers and software developers can also create custom exceptions to display particular application-specific program errors.

Custom exceptions in c++

In C++ programming, a user-created custom exception is a user-defined class method that is thrown in a program when a C++ user wants to display a specific error. These custom exceptions are caught using a try-catch block.

Why use custom exceptions in C++ programming?

  • Custom exceptions in C++ programming help you display particular exception issue errors to the C++ user.
  • Displaying particular specific custom program error conditions in the current program.
  • Making a C++ program source code logic expression easier to understand and maintain.
  • Displaying specific, essential, and important custom program exception error messages.
  • Displaying logic expressions used in normal C++ programs separately from custom error handling.

Examples of custom exceptions in a C++ program.

  • Checking invalid customer ID details
  • Checking customer bank account balances
  • Checking a patient’s age and disease
  • Checking division of a value by zero in numeric custom calculations

Creating a custom exception in a C++ program.

In the C++ programming language, a custom program exception is simply a user-defined custom class that automatically inherits from a standard exception class.

#include <exception>

class TestException : public std::exception

{

public:

const char* what() const noexcept override

{

return “Custom Exception testing”;

}

};

Explanation of a custom exception in a C++ program.

  • In this example, public std::exception inherits the behavior and properties of a standard exception class from the existing program. The
  • what() function displays or returns error message information to the current program.
  • The noexcept statement indicates that the what() function will not throw any other exceptions in the current program.
  • The override statement confirms that this function overrides the existing base class version.

Throwing a custom exception in a C++ program.

You can throw a custom program exception error message by using the throw reserved keyword in a C++ program.

throw TestException();

Example of throwing a custom program exception.

if (emp_age < 21)

{

throw TestException();

}

Let’s catch a custom exception.

try

{

throw TestException();

}

catch(const TestException& e)

{

cout << e.what();

}

Output of throwing a custom program exception.

Custom exception occurred

Complete example of throwing a custom program exception.

#include <iostream>

#include <exception>

using namespace std;

class EmpAgeException : public exception

{

Public:

const char* what() const noexcept override

{

return “Age must be at least 40 for staff promotion.”;

}

};

int main()

{

int emp_age;

cout << “Enter employee age – “;

cin >> emp_age;

try

{

if(emp_age < 40 )

throw EmpAgeException();

cout << “Eligible for staff promotion.”;

}

catch(const EmpAgeException& e)

{

cout << e.what();

}

return 0;

}

throwing a custom program exception explanation.

Enter employee age – 2

Age must be at least 40 for staff promotion.

Enter employee age – 47

Eligible for staff promotion.

Custom exception example for customer bank account balance.

#include <iostream>

#include <exception>

using namespace std;

class InsufficientAmount : public exception

{

Public:

const char* what() const noexcept override

{

return “Insufficient customer bank account balance.”;

}

};

int main()

{

double deposit_balance = 14000;

double withdraw_amount;

cout << “Please Enter your withdrawal amount – “;

cin >> withdraw_amount;

try

{

if(withdraw_amount > deposit_balance)

throw InsufficientAmount();

deposit_balance -= withdraw_amount;

cout << “Customer account remaining balance is = ” << deposit_balance;

}

catch(const InsufficientAmount& e)

{

cout << e.what();

}

return 0;

}

Explanation of custom exception example for customer bank account balance.

Please enter your withdrawal amount – 42342

Insufficient customer bank account balance.

Please enter your withdrawal amount – 1234

Customer account remaining balance is = 12766

Custom exception with a custom message.

Instead of returning fixed output message value information in a C++ program, C++ users can store and display their own custom message.

Example of custom exception with a custom message.

#include <iostream>

#include <exception>

#include <string>

using namespace std;

class TestException : public exception

{

string mesg_info;

public:

TestException(string msg)

{

mesg_info = msg;

}

const char* what() const noexcept override

{

return mesg_info.c_str();

}

};

int main()

{

try

{

throw TestException(“Invalid Patient Record ID”);

}

catch(const TestException& e)

{

cout << e.what();

}

return 0;

}

Explanation of a custom exception with a custom message.

Invalid Patient Record ID

Creating a custom exception in a C++ program without inheriting.

While it is possible to throw any type of custom exception error message in a C++ program, it is best to inherit from the std::exception class method.

Example of creating a custom exception in a C++ program without inheriting.

#include <iostream>

using namespace std;

class NonIntegerNumber

{

};

int main()

{

try

{

throw NonIntegerNumber();

}

catch(NonIntegerNumber)

{

cout << “Non-Integer number value is not allowed.”;

}

return 0;

}

Explanation of creating a custom exception in C++ without inheriting.

Non-Integer number value is not allowed.

Unique advantages of custom exceptions in C++ programs.

  • Some complex C++ programs become easier to debug and maintain.
  • Users can display meaningful and specific error messages in C++ programs.
  • Custom exceptions improve C++ program source code readability.
  • Custom exceptions help handle and manage multiple individual type errors in C++ programs separately.
  • Custom exceptions in C++ programs enhance modular programming and program maintainability.

Detail Summary of statement or method in custom exception.

Custom exception typeCustom program exception description
Custom exceptionCustom exception used as user-defined class used to represent specific runtime custom program exception error messages.
Throw keywordThrow keyword used to signal an custom program exception.
Try keywordTry keyword contains user define program source code, that may throw an custom user error exception.
Catch keywordCatch keyword use to handles the thrown keyword exception message or steps.
Std::exception classThis class library used as a base class for standard program custom exceptions; generally, it inherited by user generated custom exceptions.
What() functionWhat function used to returns a description of the custom exception as a c-style string (const char*) method.

Custom exceptions summary in C++.

Custom exceptions in the C++ programming language allow C++ users to manage custom exception error types for their desired software applications. By inheriting from the std::exception class library and overriding the what() function method, C++ users can organize or group custom error handling, display clear error messages, and maintain readable and maintainable program source code.

Leave a Reply