×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

Exception handling in C++ with Example

Learn: Types of Errors in C++ program, Exception handling in C++ with Examples.
Submitted by Amit Shukla, on June 19, 2017

In software industrial programming most of the programs contain bugs. Bigger the program greater number of bugs it contains.

Errors or Bugs in C++

The following are mainly errors or bugs that occurred in any program:

  1. Logical error:
    In this error the logic implemented is incorrect. This error occurs due to less concentration of programmer or poor knowledge of programmer regarding program.
  2. Compilation error:
    This error is occurred due to use of wrong idiom, function or structure. This error is shown at compilation time of program.
  3. Run Time error:
    This error occurred at the run time. This error occurs when program crashes during run time.
  4. Time limit error:
    This error states that program takes more time than required time. This error occurs due to use of wrong logic or lengthy method in program.

In this topic we learn that how can we control run time error using exception handing in C++.

Exceptions in C++

Exceptions are different, however. You can't eliminate exceptional circumstances; you can only prepare for them. Your users will run out of memory from time to time, and the only question is what you will do. Your choices are limited to these:

  1. Crash the program.
  2. Inform the user and exit gracefully.
  3. Inform the user and allow the user to try to recover and continue.
  4. Take corrective action and continue without disturbing the user.

Exception Handling in C++

It is not necessary that this method works for every program you write to automatically and silently recover from all exceptional circumstances, it is clear that you must do better than crashing.

Exception provides a method to control exceptional conditions (like run time error) or to control any crashed program by transferring control to some special functions called handler.

We can use following the keywords or functions to control runtime error in C++:

  1. try {}
  2. catch {}
  3. throw()

These functions are used to control any run time error.


try {} block

This block captures series of errors in any program at runtime and throw it to the catch block where user can customize the error message.

Syntax

try 
{
    //define program;
    throw(variable);
}

catch {} block

This block catches the error thrown by try block. This block contains method to customize error.

Syntax

catch
{
    //defines method to control error;
}

throw function

This function is used to transfer the error from try block to catch block. This function plays major role to save program from crashing.

Syntax

throw(variable);

Example 1

#include <iostream>
using namespace std;
int main() {
  int p, c, m, err = 0;
  string name;

  do {
    try  // using try block to check error;
    {
      cout << "Enter sudentname : ";
      cin >> name;
      cout << "Enter physics marks : ";
      cin >> p;

      if (!(p >= 0 &&
            p <= 100))  // checking that marks entered is valid or not;
      {
        throw(p);  // using throw block to transfer error to catch block;
      }
      cout << "Enter chemistry marks : ";
      cin >> c;

      if (!(c >= 0 &&
            c <= 100))  // checking that marks entered is valid or not;
      {
        throw(c);  // using throw block to transfer error to catch block;
      }

      cout << "Enter mathsmarks : ";
      cin >> m;

      if (!(m >= 0 &&
            m <= 100))  // checking that marks entered is valid or not;
      {
        throw(m);  // using throw block to transfer error to catch block;
      }
      err = 0;  // if all the conditions are false then value of error variable
                // is 0
    } catch (int e) {
      cout << "Invalid Marks" << endl;  // Showing error;
      err = 1;  // Changing value of variable to retke input;
    }

  } while (err);  // it takes input until all inputs are valid;
}

Output

Enter sudentname :Abhigyan
Enter physics marks : 95
Enter chemistry marks : 98
Enter mathsmarks : 102
Invalid Marks

Enter sudentname :Abhigyan
Enter physics marks : 95
Enter chemistry marks : 198
Invalid Marks

Enter sudentname :Abhigyan
Enter physics marks : 125
Invalid Marks

Enter sudentname :Abhigyan
Enter physics marks : 95
Enter chemistry marks : 98
Enter mathsmarks : 99

We can use multiple catch block in a single program using single try block. Following three examples explains that how can we uses multiple catch block in a single program.


Example 2

#include <iostream>
using namespace std;

int main() {
  try {
    throw(55);     // Here we input integer value;
  } catch (int e)  // This catch takes int value;
  {
    cout << "Input is Integer value " << e << endl;
  } catch (double e)  // This catch takes double value;
  {
    cout << "Input is Double value " << e << endl;
  } catch (char e)  // This catch takes character value;
  {
    cout << "Input is Character " << e << endl;
  }

  return 0;
}

Output

Input is Integer value 55

Example 3

#include <iostream>
using namespace std;

int main() {
  try {
    throw(55.5);   // Here we input double value;
  } catch (int e)  // This catch takes int value;
  {
    cout << "Input is Integer value " << e << endl;
  } catch (double e)  // This catch takes double value;
  {
    cout << "Input is Double value " << e << endl;
  } catch (char e)  // This catch takes character value;
  {
    cout << "Input is Character " << e << endl;
  }

  return 0;
}

Output

Input is Double value 55.5

Example 4

#include <iostream>
using namespace std;

int main() {
  try {
    throw('I');    // Here we input character;
  } catch (int e)  // This catch takes int value;
  {
    cout << "Input is Integer value " << e << endl;
  } catch (double e)  // This catch takes double value;
  {
    cout << "Input is Double value " << e << endl;
  } catch (char e)  // This catch takes character input ;
  {
    cout << "Input is Character " << e << endl;
  }

  return 0;
}

Output

Input is Character I

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.