+ 1

Exceptions

I’m having some issues with the exceptions code coach challenge for C++. I’m getting 3 out of the 4 test results right but I am stumped. Any help is appreciated ! https://sololearn.com/coach/872/?ref=app // my code try { if(name.size() >= 4) { cout << "Valid"; } if (name.size() <= 3 ) { cout <<"Invalid"; } } catch(int x) { if(name.size() > x) { cout <<"Invalid"; } }

25th Nov 2021, 3:21 AM
Brent Tyson
Brent Tyson - avatar
4 Réponses
+ 5
I think you might still a bit confused as to how exceptions work, because you never throw one. Try going through the lessons up to the exercise again, or consulting other sources. Think of exceptions as events fired when something abnormal/ illegal/ ... happens in your code. These events are described by some kind of value (could be an integer, a string, a custom class, ...) that describes the error that occured. If you have a portion of code where normal execution might be stopped due to an exception (either thrown by yourself, or some other function that might throw) you wrap it in a try-block (as in 'try this code and see if it works'), and handle any occuring exceptions in successive catch-blocks (multiple event-handlers are allowed). Your program then resumes after the try-catch-block. In this case, you could throw an exception if the string size does not conform to your parameters, and react to that in a catch statement, in order to print an error message.
25th Nov 2021, 12:03 PM
Shadow
Shadow - avatar
+ 2
Your question not visible to me because am non pro. Paste here question or read all the constraints again and check your code
25th Nov 2021, 3:25 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
Attach your code bit link, it's hard to analyse partial codes ... https://www.sololearn.com/post/75089/?ref=app
25th Nov 2021, 3:38 AM
Ipang
+ 1
Shadow thank you! I just solved it. Had to read from some other sources to fully understand it but your explanation helped a bunch too. Much appreciated
26th Nov 2021, 3:31 AM
Brent Tyson
Brent Tyson - avatar