|
-
January 19th, 2004, 11:02 PM
#1
Throw an exception for non-cofingurable number of vector elements...
Here is my program
PHP Code:
std::cout<<"Hey, Nina, tell me how many elements you want to use uhmm ?"<<std::endl;
std::cout<<"After you input the number, I will give you a vector "<<std::endl;
std::cin>>numElem;
std::vector<double> vec(numElem);
if(!vec){
throw std::cerr<<"Sorry, I cant do it for you, another try please"<<std::endl;
exit(1);
}
else
std::cout<<"Cool, there you go, my lady"<<std::endl;
Could you tell me if my exception thrown is correct in this case ? if not, how can I fix it ? May I have you fix it for me please ?
Thanks a lot,
Regards,
homestead
-
January 19th, 2004, 11:24 PM
#2
See here for excepting throwing and handling.
-
January 19th, 2004, 11:31 PM
#3
Re: Throw an exception for non-cofingurable number of vector elements...
Originally posted by Homestead
Here is my program
Code:
std::cout<<"Hey, Nina, tell me how many elements you want to use uhmm ?"<<std::endl;
std::cout<<"After you input the number, I will give you a vector "<<std::endl;
std::cin>>numElem;
std::vector<double> vec(numElem);
if(!vec){
There is no such thing as a "NULL" vector, therefore your check is invalid. if an exception is thrown, it would have been thrown before it even hits the if() statement. Therefore, this code should be in a try/catch block.
You shouldn't call exit like this in a C++ program. You bypass the destructors of any objects.
Could you tell me if my exception thrown is correct in this case ? if not, how can I fix it ?
Code:
#include <iostream>
#include <vector>
#include <exception>
int main()
{
int numElem;
std::cout<<"Hey, Nina, tell me how many elements you want to use uhmm ?"<<std::endl;
std::cout<<"After you input the number, I will give you a vector "<<std::endl;
std::cin>>numElem;
try {
std::vector<double> vec(numElem);
std::cout<<"Cool, there you go, my lady"<<std::endl;
}
catch(...) // Most likely, this is bad_alloc
{
std::cout << "Something went wrong";
}
}
Regards,
Paul McKenzie
-
January 19th, 2004, 11:35 PM
#4
Thanks Kheun,
Thanks Paul alot,
Regards,
homestead
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|