Sunday 9 October 2016

C++ Exception Handling

This code requires <stdexcept> header. ( alternatively you can prepend namespace “exception::” )

The following code has a simple divide function and some code handling exceptions.
This program would output:
3
error!

The divide function can throw an exception if the denominator is equal to 0. Notice how after dealing with the exception, the compiler breaks out of the code block and does not calculate the third statement.

#include "stdafx.h"// -- only for Visual Studio ( Windows)
#include <iostream>
#include <stdlib.h>
#include <stdexcept>

using namespace std;



int divide(int a, int b) {

 if (b == 0) {
  throw exception();
 }
 return (a / b);

}


int main()
{

 try {
  cout << divide(6, 2) << endl;
  cout << divide(5, 0) << endl;
  cout << divide(5, 5) << endl;
 }
 catch (...){
  cout << "error!" << endl;
 }


 system("pause");// -- only for Visual Studio ( Windows)
    return 0;
}



If you expect a particular exception, you can throw the exception value, and catch it, as shown below.
This code would output:
3
error! 0- cannot be used!


#include "stdafx.h"// -- only for Visual Studio ( Windows)
#include <iostream>
#include <stdlib.h>
#include <stdexcept>

using namespace std;



int divide(int a, int b) {

 if (b == 0) {
  throw b;
 }
 return (a / b);

}


int main()
{

 try {
  cout << divide(6, 2) << endl;
  cout << divide(5, 0) << endl;
  cout << divide(5, 5) << endl;
 }
 catch (int e){
  cout << "error! " << e << "- cannot be used!"<< endl;
 }
 

 system("pause");// -- only for Visual Studio ( Windows)
    return 0;
}

No comments:

Post a Comment