Skip to Content
✨ v2.2.4 Released - See the release notes
DocumentationMCA-418 LAB on C++ ProgrammingQ12: Demonstrate Exception Handling in C++

Q12. Demonstrate Exception Handling in C++

Question:
Write program to demonstrate use of exception handling.


My Approach

C++ me exception handling ka use errors ko gracefully handle karne ke liye hota hai.
Normally program crash ho jata hai, lekin exception handling ke sath hum error ko catch karke meaningful message display kar sakte hain aur program continue ho sakta hai.

Is program me maine ek real-life example use kiya hai:
Student Marks Calculation → agar marks invalid (negative ya greater than 100) diye gaye, to wo error throw karega aur hum usse handle karenge.


Program Code

File Name: exception_handling_demo.cpp

#include <iostream> #include <stdexcept> // for runtime_error using namespace std; class Student { private: string name; int marks; public: Student(string n, int m) { if (m < 0 || m > 100) { throw runtime_error("Invalid Marks! Marks must be between 0 and 100."); } name = n; marks = m; } void display() { cout << "Student: " << name << ", Marks: " << marks << endl; } }; int main() { try { cout << "Creating student objects..." << endl; Student s1("Rahul", 85); s1.display(); // Invalid marks, will throw exception Student s2("Intesab", 120); s2.display(); } catch (runtime_error &e) { cout << "Exception Caught: " << e.what() << endl; } catch (...) { cout << "Unknown exception occurred!" << endl; } cout << "Program continues after exception handling..." << endl; return 0; }

Sample Output

Creating student objects... Student: Rahul, Marks: 85 Exception Caught: Invalid Marks! Marks must be between 0 and 100. Program continues after exception handling...

Explanation

  1. try block → jahan pe risky code run hota hai (yaha student object banate waqt marks check hote hain).
  2. throw → agar marks invalid mile to runtime_error throw karte hain.
  3. catch block → exception ko handle karta hai aur meaningful message show karta hai.
  4. Program crash hone ke bajaye safe tarike se continue karta hai.

Real-Life Scenario

  • Student Management System me marks, roll number, ya age ka validation important hota hai.
  • Agar galti se kisi ne negative marks ya 100 se zyada marks diye, to exception handling se program crash nahi hoga, balki error message milega.
  • Ye approach robust and user-friendly applications banane me help karti hai.

Conclusion

  • Exception handling se program more reliable banta hai.
  • Errors ko handle karke program ko smoothly run karna possible hota hai.
  • Practical systems me ye feature bahut zaruri hai, especially jab hum user input handle karte hain.

Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live 

Last updated on