CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: exceptions

  1. #1
    Join Date
    Oct 2001
    Location
    Chicago, USA
    Posts
    222

    exceptions

    Hi! can you wirte your own exception class? or you have to use the predefined one?

    just a question i am not trying to write on but just for information. is it something different that you have to do? when do write or its like writing a normal class..

    Ankur


  2. #2
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: exceptions

    You can throw every kind of object, standard types like 'int', 'char', 'long' as well as structures or classes. So the answer would be "Yes you can write your own exception classes". It's nothing special or magic about it...you can write it just like you write your other classes.

    Nevertheless - the STL provides a basic exception class called 'std::exception' which should be used as a base class for your derived exception class...

    Ciao, Andreas

    "Software is like sex, it's better when it's free." - Linus Torvalds

  3. #3
    Join Date
    Apr 2000
    Location
    Frederick, Maryland
    Posts
    507

    Re: exceptions

    Try this code


    #include <iostream>
    using namespace std;

    class MyException : public exception
    {
    public:
    MyException(char* pmsg) : exception(pmsg) { }
    };

    void fun(int i) {
    if (i < 10)
    throw MyException("My Exception");
    }

    int main() {
    try {
    fun(5);
    }
    catch(exception& e) {
    cout << e.what() << endl;
    }

    return 0;
    }




    Hope it helps.



  4. #4
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: exceptions

    ... and take heed of Scott Meyers' advice (More Effective C++, Item 13) Catch exceptions by reference.

    Yes, you're perfectly at liberty to write your own exception classes (there's an article in April 2002 CUJ about an exception class that provides a stack so you can trace it).

    He who breaks a thing to find out what it is, has left the path of wisdom - Gandalf
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured