+ 1
Throw ? Exception?
hello, i'd like to know when use throw() in exception in c++? And why? thank y you
5 Respostas
+ 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
+ 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.
+ 11
We can have multiple catch blocks. So, the exception can be re-thrown by using "throw" in the catch block.
+ 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;
}
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.