Click to See Complete Forum and Search --> : exceptions
ankursaxena
May 10th, 2002, 02:04 PM
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
Andreas Masur
May 10th, 2002, 02:58 PM
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
Zeeshan
May 11th, 2002, 01:57 AM
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.
Graham
May 13th, 2002, 05:18 AM
... 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
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.