Exception Handling in C++
Exception handling in C++ provides a way to handle runtime errors gracefully and
prevent program crashes. It uses a combination of try, catch, and throw keywords
to detect and manage exceptions.
1. Basics of Exception Handling
1. try block: Encapsulates code that may throw an exception.
2. throw keyword: Used to signal the occurrence of an exception.
3. catch block: Handles the exception and defines how to respond.
2. Syntax
try {
// Code that may throw an exception
throw exception; // Exception is thrown
} catch (type exception) {
// Handle the exception
}
3. Example
Basic Example:
#include <iostream>
int main() {
try {
int a = 10, b = 0;
if (b == 0) {
throw "Division by zero!";
}
std::cout << a / b << "\n";
, } catch (const char* e) {
std::cout << "Error: " << e << "\n";
}
return 0;
}
Output:
Error: Division by zero!
4. Multiple catch Blocks
C++ supports handling multiple exception types using multiple catch blocks.
Example:
#include <iostream>
int main() {
try {
throw 10; // Change this to test different types
} catch (int e) {
std::cout << "Integer exception: " << e << "\n";
} catch (const char* e) {
std::cout << "String exception: " << e << "\n";
} catch (...) {
std::cout << "Default exception handler\n";
}
return 0;
}
Output:
Integer exception: 10
Exception handling in C++ provides a way to handle runtime errors gracefully and
prevent program crashes. It uses a combination of try, catch, and throw keywords
to detect and manage exceptions.
1. Basics of Exception Handling
1. try block: Encapsulates code that may throw an exception.
2. throw keyword: Used to signal the occurrence of an exception.
3. catch block: Handles the exception and defines how to respond.
2. Syntax
try {
// Code that may throw an exception
throw exception; // Exception is thrown
} catch (type exception) {
// Handle the exception
}
3. Example
Basic Example:
#include <iostream>
int main() {
try {
int a = 10, b = 0;
if (b == 0) {
throw "Division by zero!";
}
std::cout << a / b << "\n";
, } catch (const char* e) {
std::cout << "Error: " << e << "\n";
}
return 0;
}
Output:
Error: Division by zero!
4. Multiple catch Blocks
C++ supports handling multiple exception types using multiple catch blocks.
Example:
#include <iostream>
int main() {
try {
throw 10; // Change this to test different types
} catch (int e) {
std::cout << "Integer exception: " << e << "\n";
} catch (const char* e) {
std::cout << "String exception: " << e << "\n";
} catch (...) {
std::cout << "Default exception handler\n";
}
return 0;
}
Output:
Integer exception: 10