It’s not always clear to us why a certain function failed. That’s where exception handling using classes in C++ helps.
This method gives you a structured way to handle runtime problems so that your app doesn’t just “die,” but fails in a way that makes sense.
To write strong, enterprise-grade C++ applications, you need to be able to do this technique well.
Overview of Exception Handling Using Classes in C++
In C++, an exception occurs when something unexpected happens while the program is running. The C++ program can throw exceptions of type int or char, but using classes provides many more options.
When we talk about exception handling using classes in C++, the mechanism follows the standard “try-throw-catch” trio but elevates it by applying the principles of object-oriented programming (OOP).
Why Use Classes for Exceptions?
- Information richness: A class can contain many things. For example, a class can have error codes. A class can also have timestamps. A class can have strings that describe things, too.
- Hierarchical catching: You can create an error class. This error class is like a starting point. Then you can create error types using this error class. These specific error types are derived from the error class.
- Scope management: When an exception is thrown, destructors are automatically called for objects, which stops memory leaks.
Exception Handling Using Classes in C++ Syntax
Using classes in exceptions is basic. You create a class, which can be either a one-off or one based on the standard library, and then you use the throw keyword to create an instance of that class. You use the class you made and the throw keyword to create the instance.
Basic Syntax Structure:
C++
class MyException {
// Data and methods
};
try {
if (condition_fails) {
throw MyException();
}
}
catch (MyException e) {
// Handle the object
}
When using exception handling with classes in C++, the catch block handles the thrown object.
Types of Exception Handling Using Classes in C++
Let’s look at the three primary ways exceptions are structured within the language.
1. Standard Library Exceptions
C++ has a built-in hierarchy of exception classes that come from std::exception. These are meant to help with common mistakes like running out of memory or failing maths.
- runtime_error: Errors that can only be found while the programme is running.
- out_of_range: Thrown when trying to access elements that are not in a collection.
- bad_alloc: Thrown when new cannot get memory.
2. Custom User-Defined Classes
You can create your own classes to represent application-specific errors. This is the hallmark of professional exception handling using classes in C++ syntax, allowing you to tailor the error data to your specific business logic.
3. Hierarchical (Inherited) Exceptions
By using inheritance, you can group related exceptions. For example, a base class DatabaseError could have derived classes like ConnectionError and QueryError. This approach allows you to catch specific errors or the entire group at once.
Exception Handling Using Classes in C++ with a Custom Exception Class
Custom exceptions are the best way as you can tailor the error message to fit your application’s needs. You can create a separate class for the custom exception. However, it is better to have this class inherit from std::exception.
Step-by-Step: Creating a Custom Exception
- Include the header: Use #include <exception>.
- Inherit from std::exception: This makes your class compatible with standard catch blocks.
- Override the what() method: This virtual function returns a description of the error.
Below is the example:
C++
#include <iostream>
#include <exception>
#include <string>
class InvalidAgeException: public std::exception {
std::string message;
public:
// Constructor to set the message
InvalidAgeException(std::string msg) : message(msg) {}
// Overriding the what() method
const char* what() const noexcept override {
return message.c_str();
}
};
This exception handling using classes in C++ custom exceptions is now ready to be used in any code that needs to check a person’s age.
Exception Handling Using Classes in C++ Try Catch
With exception handling using classes in C++, you can define multiple catch blocks. This is useful when a function may throw different types of exception objects.
Multiple Catch Example:
C++
try {
// Code that might throw DatabaseError or FileError
}
catch (DatabaseError &de) {
// Handle database issues
}
catch (FileError &fe) {
// Handle file issues
}
catch (std::exception &e) {
// Handle any other standard exceptions
}
Important: Always put the most specific derived classes at the top and the base classes, like std::exception, at the bottom. The first catch block that fits the type will run.
Exception Handling Using Classes in C++ Example
Let’s look at a real-world example. Think of a programme that uses a class to figure out how to divide two numbers, but it also has to deal with dividing by zero.
C++
#include <iostream>
#include <string>
class DivisionByZero {
public:
std::string message;
DivisionByZero(): message(“Error: Cannot divide by zero!”) {}
};
int main() {
int numerator = 10;
int denominator = 0;
try {
if (denominator == 0) {
throw DivisionByZero();
}
std::cout << numerator / denominator;
}
catch (DivisionByZero &e) {
std::cout << e.message << std::endl;
}
return 0;
}
In this exception handling using classes in C++ program, the class DivisionByZero holds the error. If the denominator is zero, an instance of this class is thrown and caught.
How Exception Handling using Classes in C++ Works
Stack Unwinding is a part of the process of exception handling using classes in C++ working.
When a throw happens:
- The software pauses what it’s doing right now.
- The system searches the current scope for a matching catch block.
- If it doesn’t find what it’s looking for, it “unwinds” the stack, which means it gets rid of local items in the current function and goes to the calling function.
- This goes on until a match is found or the program ends.
Using classes makes this process safer because class destructors make sure that resources like memory buffers or file pointers are cleaned up when the programme is done.
Usage of Exception Handling using Classes in C++
Below are the most common usage:
- Memory Management: Dealing with bad_alloc when the system runs out of RAM.
- File I/O: Dealing with situations where a file can’t be found or where permission is denied.
- Network Programming: How to deal with timeouts or lost connections.
You can make your C++ code better by using classes to handle exceptions and “bulletproof” it against unexpected user input or hardware failures.
Also Read:
- Top C Plus Plus Programs List
- Addition Program In C++: Analogy-Based Examples
- Array In C++ Programming: Types of Arrays in C++ ( With Examples )
- Array Cpp: Properties, Declaration, Initialization
FAQs
Why is exception handling using classes in C++ better than using integers?
Classes let you store more information, such as error messages and state data. An integer only gives you a code that needs a separate lookup table.
What is the handling using classes in C++ syntax for multiple catches?
You can link catch blocks together, like catch (SmallError &e) { ... } and catch (LargeError &e) { ... }. Always put the most specific exception first.
How does inheritance function with C++ classes when it comes to exception handling?
If you have a base class called "Error" and a derived class called "DiskError," then "Error&" will also catch "DiskError" because of polymorphism.
What happens if a class exception is thrown but not handled?
When the stack is unwound, the program invokes `std::terminate()` if there isn't a corresponding catch block. Most of the time, this function finishes the program.
