Exception Handling, Strings
Exception Handling in C++
Introduction to error
In computing, an error in a program is due to the code that does not conform to the order expected by
the programming language. An error may produce and incorrect output or may terminate the execution
of program abruptly or even may cause the system to crash.
Types of Errors
    i.     Compile Time Error
    ii.    Runtime Error
Compile Time Error
At compile time, when the code does not comply with the C++ syntactic and semantics rules, compile-
time errors will occur. The goal of the compiler is to ensure the code is compliant with these rules.
Any rule-violations detected at this stage are reported as compilation errors. These errors are checked.
The following are some common compile time errors:
     Writing any statement with incorrect syntax
     Using keyword as variable name
     Attempt to refer to a variable that is not in the scope of the current block
     A class tries to reference a private member of another class
     Trying to change the value of an already initialized constant (final member)
        etc……….
Runtime Error
When the code compiles without any error, there is still chance that the code will fail at run time.
The errors only occur at run time are call run time errors. Run time errors are those that passed
compiler’s checking, but fail when the code gets executed. These errors are unchecked.
The following are some common runtime errors:
     Divide by zero exception
     Array index out or range exception
     StackOverflow exception
     Dereferencing of an invalid pointer
        etc……….
So, runtime errors are those which are generally can’t be handled and usually refers catastrophic failure.
Exception
An exception is a run-time error. Proper handling of exceptions is an importantprogramming issue.
This is because exceptions can and do happen in practice andprograms are generally expected to
behave gracefully in face of such exceptions.
Unless an exception is properly handled, it is likely to result in abnormal programtermination and
potential loss of work. For example, an undetected division by zeroor dereferencing of an invalid
pointer will almost certainly terminate the programabruptly.
Types
                                                                                                      1
Ramesh Prasad Bhatta, FWU
                                                                         Exception Handling, Strings
    1. Synchronous: Exception that are caused by events that can be control of program is
             called synchronous exception. Example, array index out or range exception.
    2. Asynchronous: Exception that are caused by events beyond the control of program is
             called synchronous exception. Example, Exception generated by hardware
             malfunction.
Exceptions
       Exceptions are run time anomalies or unusual condition that a program may encounter
during execution.
Examples:
               Division by zero
               Access to an array outside of its bounds
               Running out of memory
               Running out of disk space
       The exception handling mechanism of C++ is designed to handle only synchronous
exceptions within a program. The goal of exception handling is to create a routine that detects
and sends an exceptional condition in order to execute suitable actions. The routine needs to
carry out the following responsibilities:
                    1.   Detect the problem (Hit the exception)
                    2.   Inform that an error has been detected (Throw the exception)
                    3.   Receive error information (Catch the exception)
                    4.   Take corrective action (Handle the exception)
       An exception is an object. It is sent from the part of the program where an error occurs to
the part of the program that is going to control the error
                                                                                                  2
Ramesh Prasad Bhatta, FWU
                                                                    Exception Handling, Strings
The Keywords try, throw, and catch
   Exception handling mechanism basically builds upon three keywords:
             try
             catch
             throw
      The keyword try is used to preface a block of statements which may generate exceptions.
              Syntax of try statement:
                     try
                    {
                             statement 1;
                             statement 2;
                    }
      When an exception is detected, it is thrown using a throw statement in the try block.
       Syntax of throw statement
                     throw (excep);
                     throw excep;
                     throw; // re-throwing of an exception
      A catch block defined by the keyword ‘catch’ catches the exception and handles it
      appropriately. The catch block that catches an exception must immediately follow the try
      block that throws the exception
              Syntax of catch statement:
                      try
                      {
                             Statement 1;
                             Statement 2;
                      }
                      catch ( argument)
                      {
                              statement 3; // Action to be taken
                      }
              When an exception is found, the catch block is executed. The catch statement
      contains an argument of exception type, and it is optional.
                                                                                              3
Ramesh Prasad Bhatta, FWU
                                                                     Exception Handling, Strings
Guidelines for Exception Handling
       The C++ exception-handling mechanism provides three keywords; they are try, throw,
and catch. The keyword try is used at the starting of the exception. The throw block is present
inside the try block. Immediately after the try block, the catch block is present. Figure shows the
try, catch, and throw statements.
       As soon as an exception is found, the throw statement inside the try block throws an
exception (a message for the catch block that an error has occurred in the try block statements).
Only errors occurring inside the try block are used to throw exceptions. The catch block receives
the exception that is sent by the throw block. The general form of the statement is as per the
following figure.
                                                                                                4
Ramesh Prasad Bhatta, FWU
                                                                 Exception Handling, Strings
      /* Write a program to illustrate division by zero exception. */
             #include <iostream>
             using namespace std;
             int main()
             {
                    int a, b;
                    cout<<"Enter the values of a and b"<<endl;
                    cin>>a>>b;
                    try{
                              if(b!=0)
                                      cout<<a/b;
                              else
                                      throw b;
                    }
                    catch(int i)
                          {
                     cout<<"Division by zero: "<<i<<endl;
                    }
                    return 0;
             }
             Output:
             Enter the values of a and b
             2
             0
             Division by zero: 0
                                                                                          5
Ramesh Prasad Bhatta, FWU
                                                                      Exception Handling, Strings
      /* Write a program to illustrate array index out of bounds exception. */
             #include <iostream>
             using namespace std;
             int main() {
                    int a[5]={1,2,3,4,5},i;
                    try{
                            i=0;
                            while(1){
                                    if(i!=5)
                                    {
                                               cout<<a[i]<<endl; i+
                                               +;
                                    }
                                    else
                                               throw i;
                            }
                    }
                    catch(int i)
                    {
                            cout<<"Array Index out of Bounds Exception: "<<i<<endl;
                    }
                    return 0;
             }
             Output:
             1
             2
             3
             4
             5
             Array Index out of Bounds Exception: 5
                                                                                               6
Ramesh Prasad Bhatta, FWU
                                                                   Exception Handling, Strings
        /* Write a C++ program to define function that generates exception.        */
             #include<iostream>
             using namespace std;
             void sqr()
             {
                    int s;
                    cout<<"\n Enter a number:";
                    cin>>s;
                    if (s>0)
                    {
                                    cout<<"Square="<<s*s;
                    }
                    else
                    {
                                    throw (s);
                    }
             }
             int main()
             {
                    try
                    {
                             sqr();
                    }
                    catch (int j)
                    {
                             cout<<"\n Caught the exception \n";
                    }
                    return 0;
      Ouput:
            Enter a number:10
            Square=100
            Enter a number:-1
            Caught the exception
                                                                                            7
Ramesh Prasad Bhatta, FWU
                                                                  Exception Handling, Strings
User defined exception in C++
In C++, you can create a user-defined exception by deriving a new class from the
standard std::exception class. You can then throw an instance of this new class when a certain
condition is met, such as when the age limit for voting is not met.
Here is an example of how you can create a user-defined exception to validate the age limit for
voting:
#include <iostream>
#include <exception>
class AgeLimitException : public std::exception {
public:
     const char* what() const throw() {
         return "Age limit for voting not met";
};
void validateAge(int age) {
     if (age < 18) {
         throw AgeLimitException();
     else {
         std::cout << "You are eligible to vote" << std::endl;
int main() {
     int age;
     std::cout << "Enter your age: ";
                                                                                           8
Ramesh Prasad Bhatta, FWU
                                                                      Exception Handling, Strings
    std::cin >> age;
    try {
        validateAge(age);
    catch (AgeLimitException& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
    return 0;
Multiple catch statements
        #include<iostream.h>
        #include<conio.h>
        void test(int x) {
            try {
                if (x > 0)
                       throw x;
                else
                       throw 'x';
            } catch (int x) {
                cout << "Catch a integer and that integer is:" << x;
            } catch (char x) {
                cout << "Catch a character and that character is:" << x;
            }
        }
                                                                                               9
Ramesh Prasad Bhatta, FWU
                                                Exception Handling, Strings
   void main() {
       clrscr();
       cout << "Testing multiple catches\n:";
       test(10);
       test(0);
       getch();
   }
Sample Output
   Testing multiple catches
   Catch a integer and that integer is: 10
   Catch a character and that character is: x
                                                                         10
Ramesh Prasad Bhatta, FWU