CS Electrical And Electronics
@cselectricalandelectronics
All PostsCPPProgramming

Exception Handling | Try, Throw, Catch Keyword, Syntax, Code

Hello guys, welcome back to my blog. In this article, I will discuss exception handling in Cpp, what is try, throw, and catch keywords, the syntax for exception handling in C++, code on exception handling, etc.

If you require an article on some other topics then comment us below in the comment box. You can also catch me @ Instagram – Chetan Shidling.

Also, read:

  1. What Is An Inheritance In CPP, Types Of Inheritance, Code, Syntax.
  2. Recurrent Neural Network In Deep Learning With Example, Applications.
  3. Difference Between Machine Learning Artificial Intelligence Deep Learning

Exception Handling

What is an exception?

An exception is an undesirable condition that can be detected during the execution of the program. When an exception occurs the program will be terminated abnormally.

Some examples of exception are:

  1. Divide by zero.
  2. Trying to open a file that does not exist is an exception.
  3. Accessing the elements in an array with the negative index values is an exception.

This was about exception, now let’s discuss what is exception handling.

What is an exception handling?

When an exception occurs, the program will be stopped. There are some conditions where an exception occurs, but we don’t want the program to just ignore the exception and stop the program. We have to know the exceptions and take corrective actions and execute the program. This method of knowing the exceptions and bringing corrective actions and execute the program without terminating the program is called exception handling.

Let’s take one example: Program to divide the two numbers.

#include<iostream.h>
void main()
{
     int x, y, z;
     cout << "Enter x and y";
     cin >> x >> y;
     z = x/y;
    
     cout << "Quotient =" << z << endl;
}

Run 1:

Enter x and y
13 5

Quotient = 3

Run 2:

Enter x and y
13 0

Divide by zero (program will stop)

Now, observe the following points.

  1. Run 1: The program has executed properly and we got the output as 3.
  2. Run 2: The denominator is zero (0) and we got the error “Divide by zero” and therefore, it is an exception and the program is stopped or terminated.

Now, let’s see how this can be handled by using keywords such as try, catch, and throw.

Try block

Now, I will discuss “What statement will come in try block?” The statements which will come in try block are:

  1. The statements that create an exception such as “divide by zero” is situated in a try block.
  2. If an exception happens, it throws an exception before-mentioned as “divide by zero”.
  3. This block also includes the statements that should not be executed if an exception happens.

Catch block

The try block is followed by one or more catch blocks. I will discuss “What statements come in catch block?”.

  1. The block which catches an exception thrown in the try block is called a catch block.
  2. A catch block defines the type of exception it can catch and carries the code for handling the exceptions.

Syntax of try and catch block is shown below:

try
{
      //statements
}

catch (datatype1 identifier)
{
     //code which will handle exceptions
}

catch (datatype2 identifier)
{
    //code which will handle exceptions
}

Some points about try and catch blocks:

01. If no exception is thrown in a try block, the catch blocks that are connected with the try block are neglected and control is transformed to the statements following the last catch block.

02. If an exception occurs in a try block, the remaining statements in that block are neglected.

03. Once a catch block is executed, remaining catch blocks are neglected and control is transferred to the point immediately after the last catch block.

Syntax of catch block

catch (int x)
{
     //code which will handle exception
}

Following points from the above catch block:

01. The parameter x is called a catch block parameter.

02. The int type of the parameter indicated that, it can catch an exception of type int.

03. A catch block can have zero parameter or one parameter. It should not have more than one parameter.

04. The value thrown by the try block will be copied into the parameter in catch block.

Throwing an exception inside try block

The general syntax to throw an exception is:

throw expression;

The expression can be any constant value of any data type.

Let’s see one program on exception handling using try, catch, and throw keywords.

Program to divide two numbers by using exception handling

#include<iostream.h>

void main()
{
     int x, y, z;
   
     try
     {
          cout << "Enter x and y\n";
          cin >> x >> y;

          if (y == 0) throw 0;
          z = x/y;
          cout<<"Quotient ="<< z << endl;
     }

     catch(int)
     {
          cout<<"Divide by zero"<< endl;
     }
}

Observe the following points when the above program is executed:

01. If y takes value zero, a zero is thrown by the try block.

02. When throw is executed, the statements after throw are skipped and never be executed.

03. Control comes to catch block and the message “Divide by zero” is displayed.

The type of exception must match the type specified in a catch statement. If the type of exception thrown using throw does not match with the type specified in a catch, then the exception will not be caught and the program will be terminated abnormally. For example, consider the following program. Let’s take one example.

Program of mismatch of type in exception handling

#include<iostream.h>
void main()
{
     try
     {
        cout<<"Inside try"<<endl;
        throw 15;
        cout<<"This will not execute"<<endl;
     }

     catch (double a)
     {
         cout<<"Caught an exception with value = "<< a << endl;
     }
}

Output:

Inside try
Abnormal program execution

01. The exception integer 15 is thrown in try block.

02. The type of 15 which is integer do not match with type double in catch and hence we get the output “abnormal program execution”.

Also, read:

Author Profile

CS Electrical And ElectronicsChetu
Interest's ~ Engineering | Entrepreneurship | Politics | History | Travelling | Content Writing | Technology | Cooking
Share Now

CS Electrical And Electronics

Interest's ~ Engineering | Entrepreneurship | Politics | History | Travelling | Content Writing | Technology | Cooking

Leave a Reply

Your email address will not be published. Required fields are marked *