Curriculum
Course: Learn C++
Login

Curriculum

Learn C++

Text lesson

Introduction to Exception Handling in C++

In this lesson, you will learn,

  • What is Exceptions
  • Exceptions Handling Mechanism
  • Example
  • Function Throwing an Exception
  • Example

 

What is Exceptions

  • Exceptions are errors that occur at runtime.
  • Exceptions are run-time anomalies or unusual conditions that a program may encounter while executing and stop the flow of the execution of a program.

Anomalies include such as

  • running out of memory,
  • not being able to open a file,
  • a number division by zero
  • trying to initialize an object to an impossible value,
  • using an out-of-bounds index to a vector
  • or disk problems.

Exceptions are classified into synchronous and asynchronous exceptions.

Synchronous Exception

The exception occurs during the program execution due to some fault in the input data, which is called a synchronous exception.

Example – Out of range, division by zero, arithmetic exception, overflow, or underflow.

Asynchronous Exception

The exceptions caused by events or faults unrelated to the program and beyond the program’s control are called asynchronous exceptions.

Example – Disk failure, hardware malfunctions, or keyboard interrupt.

 

Exception Handling Mechanism

Exception handling mechanism provides a means to detect and report an exception circumstances. The following are the tasks performed by the mechanism.

  • Find the error (Hit the exception)
  • Inform that an error has occurred (throw an exception)
  • Receive an error information(Catch the exception)
  • Take corrective action (Handle the exception)

The following three important keywords are used to handle exceptions in C++.

  • try – Contains the block of statement that may generate exceptions
  • throw – After the exception is detected, it is thrown using a throw keyword.
  • catch – Catches the exception thrown by the throw statement and handles it appropriately.

 

Flow of Exception Handling Mechanism

The following Figure shows the flow of the exception-handling mechanism.

 

Syntax of Exception Handling

The general form of the try-catch block is as follows.

try{
    Statement 1;
    Statement 2;
    -----------
    Statement N;
    if(failure){
          throw(Object); //throw an exception
    } 
}
catch(Object){
    Statement 1;
    Statement 2;
    -----------
    Statement N;
}
//Next statements

 

Note: The catch block that handles the exception must immediately follow the try block.

When the try block throws an exception, the program leaves the control from the try block and enters the catch block to handle the exception. Exceptions are simply objects used to communicate information about the problem.

 

Example-1: Exception Handling(Division by Zero)

//ExceptionEx1.cpp
#include<iostream>
using namespace std;

int main()
{
    int a,b;
    cout<<"Enter any two numbers:n";
    cin>>a>>b;
    try
    {
        if (b==0)
            throw b;
        else
            cout<<"Result(a/b)="<<a/b<<endl;
    }   
    catch(int x){
        cout<<"2nd operand can't be 0"<<endl;
    }
    cout<<"End of the program";
}

 

Output

First Run

Enter any two numbers:
7
3
Result(a/b)=2
End of the program

The output of the first run shows successful execution. If no exception is thrown in the try block, the control is transferred to the first statement after the catch block.

Second Run

Enter any two numbers:
7
0
2nd operand can't be 0
End of the program

 

In the second run, the value of the second operand(denominator) is 0. The try block detects an exception and is thrown by the throw keyword using an object b i.e. throw b. Since an object is of int type, the catch statement containing an int type argument i.e. catch(int x) handles the exception and displays the statements.

 

Note: When the type of object thrown does not match the arg-type in the catch statement. Then the program is aborted and terminated and that exception will not be handled by the catch block.

The following code shows that the program is aborted if the catch statement does not have a matching argument with the type of object thrown.

Change the type of argument in the catch block(int->char) in the above program.

catch(char x){
     cout<<"2nd operand can't be 0"<<endl;
}

 

Output

Enter any two numbers:
7
0
terminate called after throwing an instance of 'int'

Note: When no exception is detected and thrown, the control goes to the first statement immediately after the catch block.

 

Function Throwing an Exception

An exception can be thrown from outside the try block as long as it is thrown by a function that is called from within the try block.

Syntax

return-type function-name(arg list){ //Function with exception
    ........
    throw (object); //throw exception
    ........
}
........
........
try{
    ........
    //function calling
    ........
}
catch(arg-type){
    //Handle exception
}
.......

Note: Catch block must be immediate after try block without having any code b/w them.

 

Example-2: Function Throwing an Exception

//ExceptionEx2.cpp
#include<iostream>
using namespace std;

void divide(int x, int y){
    cout<<"Inside function......"<<endl;
    if (y!=0){
         cout<<"Result(a/b)="<<x/y<<endl;
    }
    else{
        throw y;
    }
}

int main(){
    int a,b;
    cout<<"Enter any two numbers:n";
    cin>>a>>b;
    try{
        cout<<"Inside try block...."<<endl;
        divide(a,b);
    }
    catch(int i){
        cout<<"Exception caught: Divide by zero error";
    }
    return 0;
}

Output

First Run

Enter any two numbers:
11
3
Inside try block....
Inside function......
Result(a/b)=3

Second Run

Enter any two numbers:
5
0
Inside try block....
Inside function......
Exception caught: Divide by zero error

 

A try block can be localized to a function. When this is the case, each time the function is entered, the exception handling relative to that function is reset.

 

Example-3: Try-Catch Inside a Local Function

//ExceptionFuncEx1.cpp
#include <iostream>
using namespace std;
// Localize a try/catch to a function.
void ExCheck(int test){
    try{
        if(test) throw test;
    }
    catch(int i) {
        cout << "Caught Exception #: " << i << 'n';
    }
}

int main(){
    cout << "Startn";
    ExCheck(1);
    ExCheck(2);
    ExCheck(0);
    ExCheck(3);
    cout << "End";
    return 0;
}

Output

Start
Caught Exception #: 1
Caught Exception #: 2
Caught Exception #: 3
End

 

As you can see, three exceptions are thrown. After each exception, the function returns. When the function is called again, the exception handling is reset.

 

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

4.5
4.5 out of 5 stars (based on 2 reviews)
Excellent50%
Very good50%
Average0%
Poor0%
Terrible0%

 

 

December 4, 2024

Great !!

December 3, 2024

amazingg!!

 

 

Submit a Review

 

 

Layer 1
Login Categories