×
BLUE
Exception Handling in c


Exception Handling in c
  23 June 2021
Read more Like this Post.
Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution.
there is three words which used to handle the Errors. try, catch, throw. try: used for block of code where exception were thrown. catch: used for cathing particullar exception this block of code can handle the error. throw: used for throwing the exception to the catch block.

Example:

#include 
using namespace std;

class Super{
   public:
        float divide(int x, int y){
            if(y == 0){
                throw "Cannot Divide by Zero";
			}
            return x / y;
        }
};
  
int main(){
    Super super;
    try{
        cout << super.divide(10, 10) << endl;
    }catch(const char* catch_){
        cout << catch_;
    }
   return 0;
}

simple programme which have a class object divide() function which take two parameters x and y and return division of x, y. but there is a problem if the user input zero x will not divide in zero its infinity. for this problem we throw a message to catch block and catch block show the message of error. we can perform any task in catch after failure the try block.

Example

#include 
using namespace std;

int main(){
    try{
        throw 10;
    }catch(char *except){
        cout << "only catching the char throw";
    }
    catch(...){
        cout << "Exception Unknown.";
    }
}

if throwing data-type is not knowing we can declare a catch block with three dots its mean this is the default catch which not take any arguments the program throw the 10 for catch block but here not a catch block which take int type therefore it excuted on default catch block.

Example:

#include 
#include 
using namespace std;


int main(){
    vector array;
    array.push_back(12);
    array.push_back(13);
    try{
        cout << array.at(3);
    }
    catch(...){
        cout << "index out of range";
    }
}


in the example code we made a vector array which we include two values 12 and 13 in try section we call array element in index 3 which is empty in the case this is a error. if the try block fail to fetch the data from 3rd index its continue from catch block which is default and print the message.
Related Post's

cpp: function   exception handling   error catching  
Not Loaded Zohaib Jozvi
0 23 June 2021
Read Latest Post.
Read other post.