CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2003
    Posts
    220

    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<doublevec(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

  2. #2
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128
    See here for excepting throwing and handling.

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    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.
    Code:
    exit(1);
    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

  4. #4
    Join Date
    Dec 2003
    Posts
    220
    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
  •  





Click Here to Expand Forum to Full Width

Featured