Wednesday, June 29, 2016

C++ Exception Handling

Exception handling in C++ helps to prevent the unexpected problems which can happen while executing the program and if there is any error like invalid data, out of bound, overflow or any other
exceptional circumstances so that rest of the program and system in general does not get screwed up.

It mainly involves the idea:
1) Hit the exception at problem code.
2) Throw the exception
3) Catch/Receive the error info
4) handle the error or exception

Above steps gets wrapped under different block using keywords like try - to wrap the code where an exception needs to be detected & thrown.
catch - receives the exception  via exception object and handle the error.
finally -  {Not present in C++} block of code needs to be executed even if exception occurred on try block exit, used mostly to put clean up code , C++ can put those code in deconstructor.


sample code:


submitted solution from hackerrank

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

//Write your code here
class myException : public std::exception {
  virtual const char *what() const throw() {
    return "n and p should be non-negative";
  }
};

class Calculator {
   public:
    int power(int n, int p) {
        int result = 1;
        if(n <0 || p < 0)
            throw myException();
        for(int i=0; i<p;i++)
            result*=n;
        return result;
    }
};

int main()
{
    Calculator myCalculator=Calculator();
    int T,n,p;
    cin>>T;
    while(T-->0){
      if(scanf("%d %d",&n,&p)==2){
         try{
               int ans=myCalculator.power(n,p);
               cout<<ans<<endl;
         }
         catch(exception& e){
             cout<<e.what()<<endl;
         }
      }
    }   
}





No comments:

Post a Comment