Exception Handling in C++

📘 C++ 👁 28 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Exception handling is a mechanism used to handle runtime errors and maintain normal program flow.


What is an Exception?

An exception is an unexpected event that occurs during program execution, such as:

  • Division by zero

  • File not found

  • Invalid input


Keywords Used in Exception Handling

C++ uses three main keywords:

  1. try

  2. catch

  3. throw


1. try Block

Contains code that may cause an exception.

try { // risky code }

2. throw Statement

Used to throw an exception when an error occurs.

throw value;

Example:

if (b == 0) throw b;

3. catch Block

Handles the exception thrown in the try block.

catch(data_type e) { // exception handling code }

Example Program

#include using namespace std; int main() { int a, b; cin >> a >> b; try { if (b == 0) throw b; cout << a>catch (int e) { cout << "Division by zero error"; } return 0; }

Multiple catch Blocks

Used to handle different types of exceptions.

try { throw 10; } catch (int e) { cout << "Integer exception"; } catch (...) { cout << "Default exception"; }

catch(...)

Handles all types of exceptions.

catch (...) { cout << "Exception occurred"; }

Advantages of Exception Handling

  • Prevents program crash

  • Separates error-handling code

  • Improves program reliability

  • Easy debugging


Key Points

  • Exceptions occur at runtime

  • throw sends exception

  • catch receives exception

  • try encloses risky code


Conclusion

Exception handling in C++ provides a structured way to detect and manage runtime errors, making programs more robust and reliable.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes