Throw Exception in C++
During program execution, runtime problems and exceptional circumstances can be handled with exceptions in C++. The procedure entails spotting a special circumstance, producing an exception object, and then "throwing" that exception to indicate an error. Throw keyword enables the program to hand off control to the proper exception handler, which can handle the issue politely and stop the program from crashing or giving false results. To help with this, C++ provides the following keywords:
- Try: Defines a section of Code that might cause an exception.
- Catch: Describes a section of Code that is run when a certain exception is thrown.
- Throw: Throw is used to raise exceptions and to list those that a function might propagate but not be able to handle internally.
Try Block:
When defining a section of Code where exceptions might be raised, the try keyword is used, and it is then followed by one or more catch blocks that deal with the potential exceptions. The try block's goal is to include Code that could cause exceptions, enabling structured and controlled error management.
Catch Block:
The catch block is generally used to handle an exception thrown in a try block that comes before it. The catch block offers a way to react to exceptional events and take the necessary steps gracefully. The program looks for a catch block that matches the try block to handle the kind of exception thrown.
Syntax for try and catch keyword:
try {
//Code that might throw exceptions
} catch (exception_type1& execobj1) {
//Code to handle exception_type1
} catch (exception_type2& execobj2) {
//Code to handle exception_type2
} // ... (more catch blocks if needed)
Throw keyword:
When a program runs, the throw keyword is used to create and raise exceptions manually. Exceptions are a technique to deal with errors and exceptional events in a more organized and regulated way. Using the throw keyword, you can create instances of exception classes and announce the occurrence of an extraordinary circumstance.
Syntax for throw exception:
throw exception_object;
Example code:
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
try {
int var1 = 10;
if (var1 > 5) {
throw runtime_error("Number is too large.");
}
} catch (const exception& sample) {
cout << "Exception caught: " << sample.what() <<endl;
}
return 0;
}
Output:
![Throw Exception in C++](https://static.tutorialandexample.com/cpp/throw-exception-in-cpp1.png)
Explanation:
Exception handling is demonstrated in the given C++ code. An integer named var1 is given the value 10 inside a try block. If var1 is greater than 5, an if statement checks to see if it is, and if it is, a std::runtime_error exception is thrown with the message "Number is too large."
The succeeding catch block handles exceptions of the std::exception type and uses a sample. What() to record the error message. Then, cout is used to print this message. The Code serves as an example of managing exceptions, which enables regulated handling of errors during program execution. The return 0; statement marks the program's end, indicating it ran successfully.
How C++ handles Exceptions
1.Throwing an exception:
An exception is thrown when a circumstance emerges that cannot be promptly resolved within the current scope. The throw keyword is often combined with an exception object to do this. Despite frequently being an instance of a class created especially to represent the error or unusual condition, the exception object can be of any data type.
Syntax:
if (errorCondition) {
throw MyException("An error occurred.");
}
2.Catching Exceptions:
Try-and-catch blocks are used in the program to handle thrown exceptions. While a catch block is designed to catch and manage general exceptions, a try block contains the Code that might throw an exception. The program looks for a suitable catch block to handle any exceptions thrown inside the try block.
Syntax:
try {
//Code that might throw an exception
}
catch (const MyException& e) {
// Handle the exception
}
3. Exception Hierarchy:
You can catch various exception kinds using the hierarchy of exception classes provided by C++. The exception is the base class for all exceptions. To handle more specialized exception types, you can catch exception types descended from this base class.
Syntax:
try {
//Code that might throw an exception
}
catch (const exception& e) {
// Handle the exception
}
4. Custom Exception Classes:
You can create your exception classes by deriving them from exceptions or other preexisting exception classes. Custom exception classes improve code readability and help to provide useful information about individual problems.
Syntax:
Class MyException: public exception {
Public:
MyException(const char* message) : msg(message) {}
const char* what() const noexcept override {
return msg.c_str();
}
Private:
string msg;
};
How can I make a C++ Function Throw Something?
You can specify that a function throws something when it function is throwing so.
int div(int x, int y) throw(SampleException)
{
If(y==0)
throw SampleException;
return x/y;
}
Handle Any Exceptions(...)
The "three dots" syntax (...), used inside the catch block, can be used if you are unsure of the throw type used in the try block and will handle any exception type.
Code:
#include <iostream>
using namespace std;
int main() {
try {
int rollno = 21;
if (rollno >= 10) {
cout << "permission granted-you did not meet the given condition ";
} else {
throw 789;
}
}
catch (...) {
cout << "permission declined-you meet the given condition.\n";
}
return 0;
}
Output:
![Throw Exception in C++](https://static.tutorialandexample.com/cpp/throw-exception-in-cpp2.png)
Example1:
#include <iostream>
using namespace std;
void divide(int numerator, int denominator) {
if (denominator == 0) {
throw "Division by zero is not allowed.";
}
int result = numerator / denominator;
cout << "Result: " << result << endl;
}
int main() {
try {
divide(10, 0);
}
catch (const char* errorMessage) {
cerr << "Exception: " << errorMessage << endl;
}
return 0;
}
Output:
![Throw Exception in C++](https://static.tutorialandexample.com/cpp/throw-exception-in-cpp3.png)
Explanation:
- The divide function tries to divide the numerator by the denominator. The exception is thrown if the denominator is 0 and reads, "Division by zero is not allowed."
- Divide (10, 0) is called in the main Function within a try block. Due to the prohibition against division by zero, this call will result in an exception.
- "Division by zero is not allowed." is the error message sent to the catch block once it successfully catches the exception. The following message is printed: "Exception: Division by zero is not allowed."
- The caught exception message is output by the program.
Example 2:
To help you understand the C++ throw keyword
#include <iostream>
#include <exception>
using namespace std;
// Custom exception class
class SampleException : public exception {
public:
// Override the what() function to provide exception details
const char* what() const noexcept override {
return "My Custom Exception";
}
};
//Function that performs division and throws exceptions
int divide(int var1, int var2) {
if (var2 == 0)
throw 1; // Throwing an int for division by zero
if (var2 == 1)
throw SampleException(); // Throwing your custom exception
return var1 / var2;
}
int main() {
int a = 10, b = 1, c;
try {
// Attempt division and catch exceptions
c = divide(a, b);
cout << "Result of division: " << c << endl;
}
catch (int) {
cout << "Division By Zero Error" << endl;
}
catch (const SampleException& excobj) {
cout << "Division By One Error" << endl;
cout << "Exception Details: " << excobj.what() << endl;
}
cout << "End of the Program" << endl;
return 0;
}
Output:
![Throw Exception in C++](https://static.tutorialandexample.com/cpp/throw-exception-in-cpp4.png)
Explanation:
- The Code starts by adding the required headers, such as <iostream> for input and output and <exception> for managing exceptions. An individual exception class, SampleException, is defined by the exception class from which it derives. To give the exception a unique error message, it overrides the what() Function.
- When given two numbers as input, the divide function attempts to divide two integers. It looks for two specific conditions: the divisor must be either 0 or 1, in which case an instance of the special SampleException exception class is thrown to indicate division by zero.
- The variables a and b are initialized in the main Function. The program enters a try block to try the divide function's division operation.
- If the division is successful, the result is stored in variable c and written to the console inside the try block.
- The program outputs "Division By Zero Error" if a division by zero exception of type int is recognized. The program outputs "Division By One Error" and publishes the unique error message given by the what() Function of the SampleException class if a SampleException exception of type SampleException is caught.
- Whether or not an exception was handled correctly, the program outputs "End of the Programme."As a sign that the program has run successfully, it returns 0.
Throwing Custom Exceptions in C++
#include <iostream>
#include <exception>
#include <string>
// Custom exception class
class CustomException : public std::exception {
private:
std::string errorMessage;
public:
CustomException(const std::string& message) : errorMessage(message) {}
// Override the what() function to provide the exception message
const char* what() const noexcept override {
return errorMessage.c_str();
}
};
// Function that throws a custom exception
void processFile(const std::string& filename) {
if (filename.empty()) {
throw CustomException("File name is empty.");
}
// Simulate file processing
// ...
}
int main() {
std::string filename;
std::cout << "Enter a file name: ";
std::cin >> filename;
try {
processFile(filename);
std::cout << "File processing completed." << std::endl;
} catch (const CustomException& exc) {
std::cout << "Error: " << exc.what() << std::endl;
}
return 0;
}
Output:
![Throw Exception in C++](https://static.tutorialandexample.com/cpp/throw-exception-in-cpp5.png)
Explanation:
This C++ code explains how to handle errors using custom exceptions. It defines the std::exception-derived custom exception class CustomException. When creating an instance of the exception using the class, you can include an error message. To return the previously stored error message, the what() method is overridden.
When given a filename as input, the function processFile() throws a CustomException if the filename is empty. The user is prompted for a filename in the main() Function, which also calls processFile() and handles any CustomExceptions that may be thrown during file processing. It prints the error message if an exception is caught; otherwise, it processes the file or encounters no exceptions and prints a success message.
Advantages of Throw Keyword Exception
- Clear Error Signaling: A straightforward and unambiguous approach to notify mistakes and exceptional conditions in your Code is provided by exceptions. As a result, identifying and fixing issues that arise during program execution is much simpler.
- Structured error handling: By using exception handling, you may separate the logic of the main program from the Code that deals with errors. This division improves the readability and organization of the Code.
- Centralized Error Handling: Using catch blocks to centralize error-handling logic prevents error checks from being dispersed throughout your program.
- Multiple Exception Types: Because C++ enables exception hierarchies, it is possible to handle various error conditions with different code blocks by using a variety of exception types. This fine-grained processing improves the accuracy of error resolution.
- Debugging and logging: Exception objects frequently contain essential data about the error's root cause. Using this data can help troubleshoot and identify errors. There are tools to catch and log errors in many programming environments, which helps troubleshoot.
- Graceful recovery: Exception handling allows your program to recover gracefully from unforeseen circumstances. Your program can take action to manage the exception and carry on operating instead of abruptly crashing.
Disadvantages of Throw Keyword Exception
- Exception handling may result in more complicated Code. Try-and-catch blocks can obstruct the natural Flow of Code, making it more challenging to follow and comprehend, particularly in huge codebases.
- Thread safety: Handling exceptions in programs with multiple threads can be difficult. Careful synchronization and consideration of thread safety are required to prevent unexpected issues.
- Normal flow Interrupted: Exceptions obstruct a program's regular flow. Although they are crucial for error management, their use should only be reserved for extreme circumstances that deviate from the usual control flow.
Challenges in Debugging: Debugging code that contains exceptions might be difficult. Handled exceptions may result in program termination without identifying the problem's root cause.