HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Exception Handling

Definition:

In C++,exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution.The process of handling these exceptions is called exception handling. Using the exception handling mechanism, the control from one part of the program where the exception occurred can be transferred to another part of the code.

C++ Exception


An exception is an unexpected problem that arises during the execution of a program our program terminates suddenly with some errors/issues.Exception occurs during the running of the program (runtime).

C++ try and catch



Example:


    // C++ program to demonstate the use of try,catch and throw
    // in exception handling.

    #include <iostream>
    #include <stdexcept>
    using namespace std;

    int main()
  {

	// try block
	try {
		int numerator = 10;
		int denominator = 0;
		int res;

		// check if denominator is 0 then throw runtime
		// error.
		if (denominator == 0) {
			throw runtime_error(
				"Division by zero not allowed!");
		}

		// calculate result if no exception occurs
		res = numerator / denominator;
		//[printing result after division
		cout << "Result after division: " << res << endl;
	}
	// catch block to catch the thrown exception
	catch (const exception& e) {
		// print the exception
		cerr << "Exception " << e.what() << endl;
	}

	return 0;
 }
  

Output