Throw ? Exception? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Throw ? Exception?

hello, i'd like to know when use throw() in exception in c++? And why? thank y you

18th Apr 2017, 11:46 AM
Attitude
Attitude - avatar
5 Answers
+ 17
throw is a keyword used to throw statement or expression to avoid the exception in a program. #include <iostream> using namespace std; int main() { try { int motherAge = 29; int sonAge = 36; if (sonAge > motherAge) { throw 99; } } catch (int x) { cout<<"Wrong age values - Error "<<x; } return 0; } Edit: Any statement that may terminate the program abnormally during execution causes an exception which can be handled as above
18th Apr 2017, 11:54 AM
Sachin Artani
Sachin Artani - avatar
+ 11
try { throw } catch This is the outline of exception handling. The try {} tries the code for an error. If there is an error, throw is used to "throw" the expression which is caught by the catch block. The error is then handled in the catch block. So, basically the throw block is used to throw the exception so that it can be caught.
18th Apr 2017, 11:55 AM
Pixie
Pixie - avatar
+ 11
We can have multiple catch blocks. So, the exception can be re-thrown by using "throw" in the catch block.
18th Apr 2017, 12:12 PM
Pixie
Pixie - avatar
+ 1
Thank you pixie and Sachin. sometimes i use to see throw() in the tryand in the catch, why? i think we suppose to have ot in the try!! try{ ....... ...... throw; } catch { ....... throw; }
18th Apr 2017, 12:10 PM
Attitude
Attitude - avatar
0
There are also lots of objects from STL that throw exceptions. For example, if you try to access an element from a vector beyond vector size, it throws an out of bounds exception. If you run that piece of code inside a try, you can catch it and avoid the error before you get a runtime problem like segmentation fault. That way, you can fix problems without stopping the program execution.
18th Apr 2017, 5:31 PM
Denis Felipe
Denis Felipe - avatar