EXCEPTION HANDLING IN C++

INTRODUCTION

In this tutorial, we are going to learn about exceptions and different types of exceptions with their respective exception handling methods in C++.

WHAT IS AN EXCEPTION?

So, first of all, what is an exception?

An exception is a problem that arises during the flow of a problem. We can define an exception as an unexpected event that occurs during the flow of execution of the program, which disrupts the normal flow of execution of the program.

now we can doubt that exceptions are quite similar to that errors. So, what are the differences between the errors and the exceptions?

                               ERRORS                              EXCEPTIONS
 Errors are problems or faults that occur in the program, which make the behavior of the program abnormal.  An exception is an event that disrupts the normal flow of the execution of the program.
 Exceptions can be handled.  Errors cannot be handled.
 Exceptions are classified into two types. Checked exceptions.Unchecked exceptions.  Errors are always unchecked.
 In case of exceptions, the compiler will have knowledge of checked exceptions and be force to keep trying and catching blocks.  In case of errors, the compiler won’t have knowledge of the errors.
 Most of cases errors are occurred due to the lack of sources but not due to the program.  Exceptions in programs are occurred due to program code only.
 Errors occur during runtime.  Exceptions may occur either during compile time or runtime. 
Ex:OutOfMemoryError, StackOverflowError etc.Ex:ArthemeticExceptiopn, IOexception, NullPointerException etc.

Now we will look at some of the main advantages of exception handling over the normal error handling in the programming languages.

  • Normally in the error handling of the codes, mostly we use if-else blocks for error handling. But these kinds of blocks get mixed with the normal flow of the code and make the code less readable and understandable. Using the try, catch blocks in exception handling makes the code more readable and it separates the error handling from the normal flow of the code.
  • When dealing with functions, it can throw many exceptions but based on the preference, we can handle only some of them.
  • The normal flow of the code does get terminated when an exception raises. By handling those exceptions using exception handling methods, the code doesn’t get terminated even after the exceptions get invoked in the code.
See also  MULTISET CONTAINER in Cpp

 C++ EXCEPTIONS

In C++ all the standard exceptions are defined in the <exception> class which may be used inside our program by using this header. The hierarchy of the exception class is shown below.

Now we will look at the different methods used for handling the exceptions in C++.

Exception handling in C++ consists of three keywords: try, throw and catch.

Try:

The try keyword is used to define some lines of the code which is used to test for errors that can be handled later by using the catch and the throw keyword.

Let’s look at the syntax of the try block.

   try {
                                                     
                                                        // block of code;
                                                       throw parameter;

                                                 } 

Throw

The throw keyword throws an exception when any kind of error is detected in the block of code which is defined in the try block.

Catch

If any kind of error occurs when executing the block of code defined in the try block, the block of code defined in the catch block gets executed.

Let’s look at the syntax of the catch block.

   catch( datatype parameter ) {

                                                        // block of code;
                                                       // if an exception gets caught, the catch block gets executed.
 
}

Let’s look at a sample program implementing the try, catch, throw keywords.

#include <iostream>
using namespace std;
main()
{
  int x = -1;
    cout << "outside the try block\n";
    try {
      if (x < 0)
      {
         throw x;
         cout << "exception occurred, will thrown to catch block\n";
      }
    }
    catch (int x ) {
      cout << "Exception Caught \n";
   }
   cout << "end of the program";
}

The output of the program is.

See also  Operators | C++

In the above program, we defined a negative value to the variable x. in the try block, we checked whether the value of x is less than zero or not. As the value of the x is less than zero, the compiler throws an exception regarding the try block and as an exception occurs, it is caught by the catch block and the block of the code defined in the catch block got executed.

This is the working of the keywords try, catch and throw.

Now we will learn about a special block that is used to catch all kinds of exceptions invoked in the code.

Catch(…): this catch block is used to catch all the exceptions which may or may not be caught in the code.

Let’s look at a sample program implementing the catch(…) block.

#include <iostream>
using namespace std;
int main()
{
    try  {
      int a = 10;
       throw a;
    }
    catch(float a){
      cout<<"float exception";
    }
    catch (...)  {
        cout << "Default Exception\n";
    }
return 0;
}

The output of the program is.

In the above program, an integer exception is thrown but the float exception is caught in the catch block. So, that catch block is not executed. As the try block has thrown an error, the catch(…) block caught it and the code in that block got executed. This is the implementation of the catch(…) block.

Note: we should mention only three dots (…) when defining the catch(…) block.

What if the thrown exception doesn’t catch anywhere, and the catch(…) block is not defined?

The program gets terminated when there is no catch block to catch the thrown exception.

Let’s take a look

#include <iostream>
using namespace std;
main()
{
    try  {
      int a = 10;
       throw a;
    }
    catch(float a){
      cout<<"float exception";
    }
}

While running the above program, the program gets terminated after throwing the instance of a and gets terminated as it is not caught.

See also   TYPES OF INHERITANCE IN C++

Now we will look at the nested blocks of the exception handling. The C++ supports nested try/catch blocks too. In the nested try block, an exception can be re-thrown by using the throw keyword.

Let’s look at a sample program implementing the nested try/catch blocks.

#include <iostream>
using namespace std;
main()
{
    try {
        try {
          int a = 10;
            throw a;
        }
        catch (int a) {
            cout << "inner catch block handling";
            throw;
        }
    }
    catch (int a) {
        cout << "\nouter catch block handling";
    }
}

The output of the program is.

The first catch block gets executed. Later, by using the keyword throw, we re-thrown the same exception and it gets caught by the outer catch block and the code in the outer catch block gets executed. This is the implementation of the nested try/catch block.

USER-DEFINED EXCEPTIONS

In some cases, we need to generate some user-specific exceptions which are not pre-defined in C++. in such cases, we can generate our own exceptions by inheriting the exception class. This is the method of generating user-defined exceptions in C++

In order to create a user-defined exception, first, we need to include the <exception> header in our program

Let’s look at a sample program implementing the functionality of the user-defined functions.

#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception {
    public:
    char * fun () {
      cout<<" User Specific C++ Exception";
      return 0;
   }
};
main() {
    try {
      throw MyException();
    } 
    catch(MyException e) {
      e.fun();
    } 
}

The output of the program is.

  • In the above program, we included the <exception> header in our program and inherited all the properties from the exception class.
  • Later, we created a function fun() with some block of code.
  • Then we inherited all the properties from the exception class and then created an exception MyException, in which the try block throws it and the catch block handles it.
  • The catch block contains the calling of the function fun() with the parameter of the exception.

This is the implementation of the user-defined exceptions in C++.

CONCLUSION

That’s it from this tutorial. Hope you guys found it interesting. We have learned about exceptions, differences between an error and an exception, exception handling in C++ and user-defined exception in C++. happy Coding!

Leave a Comment

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

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

we provide projects, courses, and other stuff for free. in order for running we use Google ads to make revenue. please disable adblocker to support us.