C++ Exceptions
Results 1 to 3 of 3

Thread: C++ Exceptions

  1. #1
    Member
    Join Date
    Dec 2002
    Posts
    58

    C++ Exceptions

    This is something about exceptions and exception handling in C++.
    An exception occurs when we try for an invalid operation. In our code, we will put the code with chance of an illegal operation in a try block. When an illegal operation occurs, it will throw an exception which can be caught by the OS(for that we have to provide exception handling code).

    This is a simple divide by zero catcher program.
    #include <iostream>
    using namespace std;

    class Divide
    {
    public:
    class DivideError /*Exception handler class. The constructor is called when throws an exception */
    {
    };
    float divide(int x, int y)
    {
    if (y == 0)
    throw DivideError(); /*Divide by zero is not permitted. So constructor of DivideError class is called */
    else
    return x/y;
    }
    };

    int main()
    {
    int x, y;
    Divide d;
    cout << "Enter 2 numbers : " ;
    cin >> x >> y ;
    try
    {
    float f = d.divide(x,y);
    cout << f << endl ;
    }
    catch(Divide:ivideError) /* Works if an exception is thrown from the object */
    {
    cout << "Division by zero is not possible" << endl ;
    }
    return 0;
    }
    God is Love

  2. #2
    Senior Member tampabay420's Avatar
    Join Date
    Aug 2002
    Posts
    953
    cool post, next time try using [ code ] [ /code ] (with out the spaces)...
    that should keep the spaces and make it much easier for us to read?

    -take it easy
    yeah, I\'m gonna need that by friday...

  3. #3
    Member
    Join Date
    Dec 2002
    Posts
    58
    When it is not in a class , exceptions are handled this way
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
      int pid;
      char pwd[10] ;
      try
      {
        cout << "Enter login Id : " ;
        cin >> pid ;
        if (pid != 101)
          throw pid;
        cout << "Enter password : " ;
        cin >> pwd;
        if (strcmp(pwd, "abcd") != 0)
          throw 'I' ;
      }
      catch(int)
      {
        cout << "Invalid login Id" << endl;
      }
      catch(char str)
      {
        cout << "Invalid Password" << endl;
      }
     return 0;
    }
    God is Love

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •