Runtime Errors , program के running time पर आती हैं , run time errors को ही exceptions कहते हैं। और सिर्फ इन्ही errors को हम handle कर सकते हैं। c++ में try , catch और throw keyword की help से हम किसी exception को handle करते हैं।

  • try : तो try{ } block के अंदर हम अपना सारा code / logic लिखते हैं , जिस code में exception आने के chances रहते हैं उस code को try{} block में ही लिखते हैं।

  • catch : जब भी कोई Run Time Error आती है तो us error को हम catch{} block में handle करते हैं जहां हमें Error message मिलता है।

  • throw : throw keyword की help से हम program execution को catch block में deposit करते हैं , या कह सकते हैं condition के according errors generate करने के लिए throw का use किया जाता है।

c++ exception handling example

CopyFullscreenClose FullscreenRun
#include <iostream>
using namespace std;
int main() {
  try {
    int num1, num2;
    cout << "Enter number1 : ";
    cin >> num1;
    cout << "Enter number2 : ";
    cin >> num2;
    
    // raise error if, num2 is less than or equal to 0;
    if(num2 <= 0) {
      throw "num2 can not be less than 0";
    }
    cout << num1 / num2;
  }
  catch(const char* message) {
    cout << "Exception caught : ";
    cout << message;
  }
  return 0;
}
Output
Run first time : 
-------------
Enter number1 : 50
Enter number2 : 10
5

Run second time : when number2=0
--------------------------------
Enter number1 : 12
Enter number2 : 0
Exception caught : num2 can not be less than 0

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers