C++ language

Exception Handling in C++
Previous Home Next

Exception means run time error. To handle run time error, we use exception handling. Exception handling provides us the facility to transfer control from one part of program to another.

To handle run time error we use 3 keywords:-

  1. Try
  2. Catch
  3. Throw
  1. Try:- Try block contains the code for which exception will occur. This block followed by one or more catch block.
  2. Catch:- Catch block is use to handle the exception.
  3. Throw:- Throw keyword is use to raise the unchecked exception. Run time error is thrown by using throw keyword from inside try block.

Syntex:

try
{
   no. of statements and logic
}
catch (Exception E1)
{
   no. of statements
}
catch (Exception E2)
{
   no. of statements
}
catch (Exception En)
{
   no. of statements
}

 

Example:

# include <iostream.h>
# include <conio.h>
void main ()
{
   int a,b,c ;
  Cout << "Enter the value of variable a";
  Cin >> a ;
  Cout << "Enter the value of variable b";
  Cin >> b ;
  try
    {
      c = a/b ;
     
      Cout << c ;
    }
  else
   {
      throw (a/b) ;
   }

  catch (exception e)
   {
       Cout << "Divide by zero is an error";
   }
}
Output
Enter the value of variable a  10
Enter the value of variable b  0

Divide by zero is an error
Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: