How to Use Try Catch in C++ for Error Handling
In C++, use
try blocks to wrap code that might cause errors and catch blocks to handle those errors when they happen. This lets your program respond to problems without crashing.Syntax
The try block contains code that might throw an exception. The catch block follows and handles the exception if it occurs. You can have multiple catch blocks for different error types.
- try: Start a block of code to test for exceptions.
- throw: Used inside
tryto signal an error. - catch: Defines how to handle the thrown error.
cpp
try { // code that may throw an exception throw exception_object; } catch (ExceptionType1& e1) { // handle ExceptionType1 } catch (ExceptionType2& e2) { // handle ExceptionType2 }
Example
This example shows how to catch a division by zero error by throwing an exception and handling it gracefully.
cpp
#include <iostream> #include <stdexcept> int divide(int a, int b) { if (b == 0) { throw std::runtime_error("Division by zero"); } return a / b; } int main() { try { int result = divide(10, 0); std::cout << "Result: " << result << std::endl; } catch (const std::runtime_error& e) { std::cout << "Error caught: " << e.what() << std::endl; } return 0; }
Output
Error caught: Division by zero
Common Pitfalls
Common mistakes include catching exceptions by value instead of by reference, which can cause slicing and lose error details. Another pitfall is not catching specific exceptions, leading to unexpected program termination. Also, avoid empty catch blocks that silently ignore errors.
cpp
/* Wrong way: catching by value */ try { throw std::runtime_error("Error"); } catch (std::runtime_error e) { // copies exception std::cout << e.what() << std::endl; } /* Right way: catch by const reference */ try { throw std::runtime_error("Error"); } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; }
Quick Reference
- try: Wrap code that might fail.
- throw: Signal an error.
- catch: Handle the error.
- Catch exceptions by
const referenceto avoid slicing. - Use specific exception types for clearer error handling.
Key Takeaways
Use
try to wrap code that may throw exceptions and catch to handle them.Always catch exceptions by const reference to preserve error details.
Throw exceptions with meaningful messages to help debugging.
Avoid empty
catch blocks that hide errors silently.Use multiple
catch blocks to handle different error types specifically.