Introduction to C++ | Exception Handling
Try/Catch in C++
C++ provides a mechanism for handling exceptions using try, catch, and throw keywords. Exception handling allows you to handle runtime errors gracefully, ensuring that your program doesn't crash unexpectedly.
What is Exception Handling?
Exception handling in C++ is a way to respond to runtime errors, such as invalid inputs, memory allocation failures, or other unforeseen issues, without terminating the program abruptly. You can use a try block to write the code that may throw an exception, and a catch block to handle the exception if it occurs.
Syntax of an Interface
Syntax
try {
// Code that may throw an exception
} catch (const exception_type& e) {
// Code to handle the exception
}
How Try/Catch Works?
- Try Block: Contains the code that might throw an exception.
- Catch Block: Catches and handles the exception. It follows the try block and executes only if an exception is thrown.
- Throwing Exceptions: If an error is detected within the try block, an exception is "thrown" using the
throw
keyword.
Example: Basic Try/Catch Block
Code Example: Basic Try/Catch
#include <iostream>
using namespace std;
int main() {
try {
int x = 10;
int y = 0;
if (y == 0) {
throw "Division by zero error!"; // Throwing an exception
}
int result = x / y; // This won't be executed
cout << "Result: " << result << endl;
} catch (const char* msg) {
cout << "Error: " << msg << endl; // Catching the exception
}
return 0;
}
Output
Multiple Catch Blocks
You can have multiple catch
blocks to handle different types of exceptions. C++ allows you to catch different types of exceptions using specific exception classes or types.
Code Example: Multiple Catch Blocks
#include <iostream>
using namespace std;
int main() {
try {
int choice;
cout << "Enter 1 for Arithmetic error, 2 for Invalid input: ";
cin >> choice;
if (choice == 1) {
throw 20; // Throwing an integer exception
} else if (choice == 2) {
throw "Invalid input"; // Throwing a string exception
} else {
throw 0; // Unknown error
}
} catch (int e) {
cout << "Caught an integer exception: " << e << endl;
} catch (const char* msg) {
cout << "Caught a string exception: " << msg << endl;
} catch (...) {
cout << "Caught an unknown exception!" << endl;
}
return 0;
}
Output
Caught an integer exception: 20
Throwing Custom Exceptions
You can also define custom exceptions by creating your own exception classes. For this, you can use inheritance from the base class std::exception
.
Code Example: Custom Exception
#include <iostream>
#include <stdexcept>
using namespace std;
class MyException : public exception {
public:
const char* what() const throw() {
return "This is a custom exception!";
}
};
int main() {
try {
throw MyException(); // Throwing custom exception
} catch (MyException& e) {
cout << "Caught custom exception: " << e.what() << endl;
}
return 0;
}
Output
Pro Tip:
💡 Pro Tip
It is a good practice to catch exceptions by reference, especially when working with custom exceptions, to avoid slicing and ensure you handle the exact exception type.