how to use "logic_error"?

I have very little knowledge about this subject so do not judge me.
Can somebody explain me why we use std::logic_error?
I mean we can use try and catch without logic_error to do the same thing as far as I know?
Or maybe use a loop to check for error or maybe use switch.

What does it do exactly, I also could not find any useful info about the syntax of it.

For example can I use it for this situation if so how

1
2
3
4
5
6
7
8
//lets say input.write can't take more than 10 as parameter
//So how can I implement logic_error to help me
try {
  input.write(99999);
  //code here
} catch( std::logic_error ) {
// code here
}
In your case, you would have the write() method throw and std::logic_error if it checks the parameter and finds that it is greater than 10. The point is you can use exceptions in cases where there is no way you can continue with the program internally.
Thank you for your answer.

So I will have to say.

1
2
3
4
5
6
7
8
void Class::write(int amount) {
if(amount>InputMax) {
throw logic_error("Error");
}
else {
InputMax+=amount;
}
}


And than
1
2
3
4
5
6
7
8
9
10
11
12

try {
  input.write(99999);
  //actual code that will work if the input is <10

} catch( std::logic_error ) {

//And here I suppose to write something that will make the code work or at least cout a warning


}


Am I correct or is it wrong?

Also if I have, let's say 5 more logic error throws.

How come compiler can understand and match the thrown logic error with the code block that it should run?

I mean I can have another method that has a throw logic_error in it, and that try and catch also includes that method too.
So how come compliler will understand which code block to run?
Is there any way to specify the code block to run if the throw is matched?

Sorry for millions of questions.



Topic archived. No new replies allowed.