C++ Exception Handling

When we execute our program, there may be a change of error occur. Types of errors:

  1. Compile Time Error: Error that occurs during compile time is known as compile time error. Compile time error, generally, are misspell a keyword, syntax incorrect or missing punctuation also known as Syntax error. Compiler will find all these errors and report to you, when you compile your program.
    Punctuators: ! % ^ & * ( ) + = { } \ ~ [ ] ; ' : " < > ? , . / #
  2. Logical Error: At the time of program execution, there is no compile time error, but even if the result is not accurate than it is known as logical error. For example: incorrectly operator implemented, using a variable before its initialization etc. They are hard to handle and locate. So you should be careful in writing program because it takes lot of time to fixing it. All these type of errors are checked by programmer only.
  3. Runtime Error: Errors that occurs during the execution of a program are known as runtime errors. These errors stop the execution of the program known as abnormally terminated. It halts the programs when it encounters. These errors are like mismatch of data type, array out of range, invalid input, divide by zero etc.
  4. Linker Error: Errors occur during linking process are known as linker error like if you have not included stdio.h file. The program will compile properly but will fail to link system library.

Exception Handling is use to handle Runtime error. It uses try, catch, throw keywords.

Example 1: Exception handling

#include <iostream>
using namespace std;
int main()
{
    int a, b, c;
    cout<<"Enter 2 Numbers: ";
    cin>>a>>b;
    try
    {
        if(b==0)
        {
            throw b;
        }
        else
        {
            c=a/b;
            cout<<"Division = "<<c;
        }
    }
    catch(int n)
    {
        cout<<"Cannot Divide by 0";
    }
    return 0;
}
Output 1:
Enter 2 Numbers: 20
4
Division = 5

Output 2:
Enter 2 Numbers: 20
0
Cannot Divide by 0