Hi,
I am trying to define my own exceptions derived from logic_error.
I am trying to make two exceptions underflow and overflow.
Underflow will be thrown if class.a<0,
for class.a = class.b-class.c
Overflow will be thrown if class.a>MAX,
class.a= class.b+class.c
(MAX is the largest "class.a" can be)
(They might already exist but assignment is to make your own exceptions)
So far this is what I come up with,
Am I too far away or close?
I could not find enough info about logic_error, and the ones I found
do not talk about deriving your own exception.
This is what I am trying to do
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
#include "Class.h"// header file for the class
#include <stdexcept>
#include "Overflow.h"
using namespace std;
using namespace cs52;
void main(){
try {
Class a = b - c;
cout << "Try catch not working" << endl;
} catch( UnderFlow ) {
cout<<"UnderFlow working";
} catch( std::logic_error ) {
// the catch above should have caught this error, not this one!
cout << "UnderFlow not working" << endl;
}
}
|
Header
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#ifndef UNDERFLOW_H
#define UNDERFLOW_H
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;
namespace cs52{
class UnderFlow:public logic_error {
public:
UnderFlow();
virtual void string what();// or something else here?
protected:
//Do I need something protected here?
};
}
#endif
|
Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <string>
#include <iostream>
#include <stdexcept>
#include "Underflow.h"
using namespace std;
namespace cs52{
UnderFlow::UnderFlow(): logic_error()//What should I write as argument for logic_error
{}
string UnderFlow::what(){}
}
|
Another header try,
this one is for OverFlow
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#ifndef OVERFLOW_H
#define OVERFLOW_H
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;
namespace cs52{
class OverFlow:public logic_error {
public:
OverFlow(string what_arg);
const char* what(what_arg)
{return "OverflowingFlashDriveException\n";}
//virtual void string what();
};
}
#endif
|
Thank you in advance.