Handling Exceptions

In C++ programming, errors can occur during the execution of code, and it's essential to handle these errors gracefully. These errors may result from incorrect input or other unforeseen circumstances. These error situations are commonly referred to as exceptions in C++.

Syntax:

try {
    // here goes the code
    //throw exception if any error 
    throw exception; 
}
catch () {
    //Code to handle errors
}

What happens in try catch block:

  1. In try block, we write our code that may throw an exception.
  2. If there is a problem in code, the throw keyword throws an exception.
  3. The catch block has the code which is to be executed in case of error.

Example:

Let us explore an example.

exception.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
	long long int ph;
    try{
		cout<<"Enter your phone number "<<endl;
		cin>>ph;
		if(ph){
			cout<<"0"<<ph<<endl;
		}
		else
		throw 505;
		}
		catch(...){
			cout<<"Invalid Phone numer."<<endl;
		}

    return 0;
}

In this example, the variable named ph which takes input phone number is integer type. But if user inputs some other data type, it will throw an error and we will get error message.

Another Example:

exception.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
	  int con;
	  cout<<"Press 1 if you are human.";
	  cin>>con;

    try {
  	  if (con == 1) {
    	  cout << "Access granted.";
  	  } else {
    	  throw 505;
  	  }
    }
	  catch (...) {
  		  cout << "Access denied.\n";
	  }
    return 0;
}

Why Handling Exceptions?

  1. Error Handling: Exception handling helps us to separate the error handling code from the normal flow of the program making code more readable. If we do not use exception handling to handle errors, error results in the termination of our code.
  2. User Friendly: When we create applications with a user interface, exception handling allows us to provide meaningful message to the user if error occurs. It will improve the user experience.
  3. Readable Code: Exception handling allows us to write a clearer code. In this way, code becomes more readable and manageable.