info@tutsfinder.in



Exception Handling


Exception is an event that occurs during an execution of a program that disrupts the normal flow the program.

To handle these exceptions, there be a concept in java that is Exception handling; it maintains the normal flow of the program.

Main advantage of exception handling is that it’s maintain the normal flow of the program and Separate error handling code form normal code.

Exception can be occurred due to wrong input data e.g. divide by zero.

There are three keywords in C++ associated with exception handling

Try – To make statements exception safe, enclose them within a try block and handle the exceptions that emerge out of try block in the catch block.

void func()
{
	try{
		int* p= new int;
		*p = 999;
		Delate p;
}
	catch(Exception e){
		cout << e << endl;
}
}

Catch – catch block is used to catch the exception when try block throws an exception.

catch
{
	//methods to control error;
}

Throw - Throw keyword allows the user to throw an exception or any class .


Program to show how try/catch block works

#include <iostream> 

using namespace std;  
float divide(int x, int y) {  
   if( y == 0 ) {  
      throw "Exception occured!";  
   }  
   return (x/y);  
}  
int main () {  
   int i = 5;  
   int j = 0;  
   float k = 0;  
   try {  
      k = divide(i, j);  
      cout << k << endl;  
   }catch (const char* e) {  
      cerr << e << endl;  
   }  
   return 0;  
}


Output:

Exception occured!


Exception handling using try/cath throw keyword

#include <iostream>
using namespace std;
int main()
{
    int a=5, b=0, c;
    
    try 
    {
        if(b == 0)
        {
            
            throw "exception occured  ";
            c = a/b;
        }
    }
    catch(char* ex) 
    {
        cout << ex;
    }
    return 0;
}


Output:

Exception occured


#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream fs; 
    fs.open("C:\xyz.txt",ios::out);  // Creating new file
    if(!fs) 
    {
        cout << "File creation failed";
    }
    else
    {
        cout << "New file created";
        fs.close();
    }
    
    return 0;
}


Output:

New file created

Reading from a file –



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

int main () {  
  string str;  
  ifstream filestream("xyz.txt");  
  if (filestream.is_open())  
  {  
    while ( getline (filestream,str) )  
    {  
      cout << str << endl;  
    }  
    filestream.close();  
  }  
  else {  
      cout << "File opening is fail !" << endl;   
    }  
  return 0;  
}

Writing to a file –


#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream fs; 
    fs.open("C:\xyz.txt",ios::out);  
    if(!fs) 
    {
        cout << "File creation failed";
    }
    else
    {
        cout << "New file created successfully";
        fs << "TutsFinder";    
        fs.close(); 
    }
  
    return 0;
}