AppDividend
Latest Code Tutorials

C++ Exception Handling Example | Exception Handling In C++

0

C++ Exception Handling Example | Exception Handling In C++. Exceptions provide a method to react to exceptional circumstances and errors (like runtime errors) inside the programs by transfer control to special functions called handlers. A portion of the code is placed under the exception inspection for catching the exception. This technology offers a securely integrated approach to avoid the unusual predictable problems that arise while executing a program. It was not a part of an original C++. It is the new feature that ANSI C++ used in it. Nowadays almost all C++ compilers support this feature.

C++ Exception Handling

The exception is an issue that arises during the execution of any program. C++ exception is the response to an exceptional circumstance that occurs while the program is running, such as an attempt integers to divide by zero. Exceptions provide the way to transfer the control from one part of the program to another. Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution.

#TYPES OF EXCEPTION:-

  1. Synchronous exceptions
  2. Asynchronous exceptions

Synchronous exceptions fall the category of error such as: out of range index and overflow. 

Asynchronous exceptions are those errors caused by the function or events beyond the control of the program.

The main motive is to take the appropriate action of exceptional handling concept to provide the means to detect and report an exception.

#Performs the following tasks to separate the error handling code

  1. Find and hit the problem (exception)
  2. Inform that the error has occurred (throw an exception)
  3. Receive the error information (Catch the exception)
  4. Take corrective actions (handle exception)

#The error handling mechanism consists of two parts. These are:

  1. If we want to detect the errors
  2. If we want to throw exceptions and then take appropriate actions

#C++ Exception built on three keywords: try, catch, and throw

#try

The try block is used to identify a block of code for which the exception will be applied. I can be followed by one or more exception.

#throw

A program throws the exception when a problem is detected inside the program. A “throw” keyword is used for this.

#catch

A program catches an exception where programmers want to handle the problem with exception handling with the help of “catch” keyword.

The Catch blocks catching exceptions must follow the try block which throws the exception.

The general form of these two blocks is as follows:

#Syntax

try
{
    throw exception;
}

catch(type arg)
{
    //some code
}

If a try block throws the exception, then program firstly control then leaves a block and enters into a catch statement of the catch block. The catch block is executed for handling an exception If the type of object thrown matches the argument type in the catch statement. 

#Example of exception handling

See the following code example.

#include <iostream>
using namespace std;

double division(int var1, int var2)
{
  if (var2 == 0)
  {
    throw "Division by Zero.";
  }
  return (var1 / var2);
}
int main()
{
  int a = 30;
  int b = 0;
  double d = 0;
  try
  {
    d = division(a, b);
    cout << d << endl;
  }
  catch (const char *error)
  {
    cout << error << endl;
  }
  return 0;
}

See the following output.

 

Exception Handling In C++

#Throwing Exceptions

Exceptions can be thrown anywhere within the code block using a throw statement. The operand of a throw statement determines the type for an exception and can be any expression, and the type of the result of the expression determines a kind of exception thrown.

See the following example.

double division(int x, int y) {
   if( y == 0 ) {
      throw "Division by zero condition!";
   }
   return (x/y);
}

#Catching Exceptions

The catch block following a try block catches any exception. You can specify that what type of exception you want to catch, and it is determined by the exception declaration that appears in the parentheses following the keyword catch.

See the following example.

try {
   // protected code
} catch( ExceptionName e ) {
  // code to handle ExceptionName exception
}

The following is the example, which throws the division by zero exception and we catch it inside the catch block.

#include <iostream>
using namespace std;

double division(int x, int y)
{
  if (y == 0)
  {
    throw "Oops!! Division by zero condition!";
  }
  return (x / y);
}

int main()
{
  int a = 21;
  int b = 0;
  double dividend = 0;

  try
  {
    dividend = division(a, b);
    cout << dividend << endl;
  }
  catch (const char *msg)
  {
    cerr << msg << endl;
  }
  return 0;
}

See the following output.

 

C++ Exception Handling Example

#Define New Exceptions

You can define your exceptions by inheriting and overriding exception class functionality. Following is an example, which shows how you can use the std::exception class to implement your exception in standard way. See the following program.

#include <iostream>
#include <exception>
using namespace std;

struct CustomException : public exception
{
  const char *what() const throw()
  {
    return "This is C++ Exception";
  }
};

int main()
{
  try
  {
    throw CustomException();
  }
  catch (CustomException &c)
  {
    std::cout << "CustomException caught" << std::endl;
    std::cout << c.what() << std::endl;
  }
  catch (std::exception &c)
  {
    // Other errors
  }
}

In the above example, we have used C++ Structs.

#Advantages of Exception Handling

  1. Programmers can deal with an exception at some level within the program.
  2. If the error can’t be dealt with at one level, then it will automatically be sent to show at the next level of program, where it can be dealt with.

#Why Exception Handling is used

  1. Separation of Error Handling code from Normal Code.
  2. Functions/Methods can handle any exceptions they choose.
  3. Grouping of Error Types: In C++.

#C++ Standard Exceptions

C++ provides the list of standard exceptions defined in <exception> which we can use in our programs.

No Exception & Description
1 std::exception

This exception and the parent class of all the standard C++ exceptions.

2 std::bad_alloc

This exception can be thrown by new.

3 std::bad_cast

This exception can be thrown by a dynamic_cast.

4 std::bad_exception

This exception is useful to handle unexpected exceptions in a C++ program.

5 std::bad_typeid

This exception can be thrown by typeid.

6 std::logic_error

This exception that theoretically can be detected by reading the code.

7 std::domain_error

This exception is thrown when the mathematically invalid domain is used.

8 std::invalid_argument

This exception is thrown due to invalid arguments.

9 std::length_error

This exception is thrown when a too big std::string is created.

10 std::out_of_range

This exception can be thrown by the ‘at’ method, for example a std::vector and std::bitset<>::operator[]().

11 std::runtime_error

This exception that theoretically cannot be detected by reading the code.

12 std::overflow_error

This exception is thrown if a mathematical overflow occurs.

13 std::range_error

This exception occurs when you try to store a value which is out of range.

14 std::underflow_error

This exception is thrown if a numerical underflow occurs.

Finally, C++ Exception Handling Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.