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.
#include <iostream>
#include "Class.h"// header file for the class
#include <stdexcept>
#include "Overflow.h"
usingnamespace std;
usingnamespace 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;
}
}
The exceptions classes don't need to be elaborate. You can put what you like in there. It all depends on what information you want to get out of them.
If all you want to know is that you had an overflow or underfow, they don't need any state of their own. If fact, there is already a std::overflow_error and std::underflow_error that you can use.
If you need state, for example the parameters that were used when the overflow,underflow occured, then you need to write your own, but make them derive from std::overflow_error and std::underflow_error respectively instead of logic_error (as they are in fact, runtime_errors not logic_errors).
Our professor for some reason wants us to use logic_error.
I figured out overflow and underflow already exist but, assignment is to make your own exceptions out of logic_error which will inherit something from logic_error.
As long as they inherit something from logic_error, its fine.
They just have to print something like "OverFlow Exception" and the state.
The book that I am using almost has no information about logic_error(Walter J. Savitch-Problem Solving with C++ 7th ed.)
By the way, you said they were runtime_errors but isn't it true that it was programmers logic error that cause the problem.
----------------------------------------------
For example
a=0,b=2,c=4
a=b-c
And a can't take negative numbers.
---------------------------------------------
Is this runtime or logic error?
If you define a cs52::overflow_error based on std::logic_error, you're just gonna confuse yourself and others when it can't be caught from std::overflow_error.