Like Tree8Likes
  • 1 Post By grumpy
  • 2 Post By laserlight
  • 1 Post By phantomotap
  • 2 Post By grumpy
  • 2 Post By phantomotap

try-catch is not working

This is a discussion on try-catch is not working within the C++ Programming forums, part of the General Programming Boards category; good evening. Code: #include <iostream> using std::cout; using std::cin; using std::endl; #include <exception> using std::exception; int main() { int val1, ...

  1. #1
    Tears of the stars thames's Avatar
    Join Date
    Oct 2012
    Location
    Rio, Brazil
    Posts
    193

    Question try-catch is not working

    good evening.

    Code:
     
    #include <iostream> 
    using std::cout; using std::cin; using std::endl;
    
    #include <exception> 
    using std::exception; 
    
    int main() 
    { 
       int val1, val2, result; 
       val1 = val2 = result = 0;
       
       cout << "Please enter two values separated by spaces:\n"; 
       while(cin >> val1 >> val2) 
       { 
         try 
         { 
            result = val1 / val2; 
            cout << "Result: " << result << endl;
         } 
         catch(exception err) 
         { 
           cout << "Error: Second value must be higher than 0\n";
           cout << err.what() 
                << "\nTry again? Enter y or n" << endl; 
           char c; 
           cin >> c; 
           if(!cin || c == 'n') 
             break;      
         }              
       }                    
       return 0;
    }
    Code:
    thames@semaht ~/C++/Exceptions $ g++ -g -Wall exc2.cc -std=c++11
    thames@semaht ~/C++/Exceptions $ valgrind ./a.out
    ==4606== Memcheck, a memory error detector
    ==4606== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
    ==4606== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
    ==4606== Command: ./a.out
    ==4606== 
    Please enter two values separated by spaces:
    5 0
    ==4606== 
    ==4606== Process terminating with default action of signal 8 (SIGFPE)
    ==4606==  Integer divide by zero at address 0x402CB32CD
    ==4606==    at 0x400E07: main (exc2.cc:17)
    ==4606== 
    ==4606== HEAP SUMMARY:
    ==4606==     in use at exit: 0 bytes in 0 blocks
    ==4606==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
    ==4606== 
    ==4606== All heap blocks were freed -- no leaks are possible
    ==4606== 
    ==4606== For counts of detected and suppressed errors, rerun with: -v
    ==4606== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
    Exceção de ponto flutuante

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,290
    The result of an integer division by zero (or any numeric division by zero) is undefined behaviour, not (necessarily) throwing an exception.

    If you want an exception to be thrown then, before doing the division, throw an exception if val2 is zero.
    thames likes this.
    Right 98% of the time, and don't care about the other 3%.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,717
    Don't do this:
    Code:
    #include <iostream>
    using std::cout; using std::cin; using std::endl;
     
    #include <exception>
    using std::exception;
    using declarations should not come before header inclusions as they could change the meaning of the code included. Rather:
    Code:
    #include <iostream>
    #include <exception>
    
    using std::cout;
    using std::cin;
    using std::endl;
    using std::exception;
    Quote Originally Posted by thames
    try-catch is not working
    What exception did you expect to catch? If it was the division by zero error, then no, there is no exception thrown from that unless you enable something compiler specific. Besides this, if it was "Second value must be higher than 0", then certainly there would be no exception thrown just for dividing by a negative value.

    I suggest that you simply check what is the value of val2.
    thames and Elysia like this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,258
    O_o

    C++ doesn't really have native numeric exceptions. (Yes, some compilers offer it as an option, but it is not standard.)

    Do the exception stuff manually if you want to handle such an error condition with an exception. (Possibly putting the numeric logic into a class.)

    However, processing input for validity isn't and shouldn't be part of the logic of values. Do your job, and confirm the validity of input before you start using the input.

    Soma
    rogster001 likes this.

  5. #5
    Tears of the stars thames's Avatar
    Join Date
    Oct 2012
    Location
    Rio, Brazil
    Posts
    193
    still, it's not wrong to throw an exception there, right? (I was studying the exception chapter)

    Code:
     
    #include <iostream> 
    #include <exception> 
    
    using std::cout; 
    using std::cin; 
    using std::endl;
    using std::exception; 
    
    int main() 
    { 
       double val1, val2, result; 
       val1 = val2 = result = 0;
       
       cout << "Please enter two values separated by spaces:\n"; 
       while(cin >> val1 >> val2) 
       { 
         try 
         { 
            if(val2 == 0) 
            { 
              throw exception();    
            }     
            result = val1 / val2; 
            cout << "Result: " << result << endl;
         } 
         catch(exception err) 
         { 
           cout << "Error: Second value must be higher or lower than 0\n";
           cout << err.what() 
                << "\nTry again? Enter y or n" << endl; 
           char c; 
           cin >> c; 
           if(!cin || c == 'n') 
             break;      
         }              
       }                    
       return 0;
    }

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,290
    Not wrong, but certainly not recommended.

    Exceptions are generally intended for reporting an error that can't be handled by the code that detects the error. The cost of exceptions depends on quality of implementation of your compiler but, as a rule of thumb, probably cost more than is justifiable if any alternative options are available.

    In other words, view exceptions as an error reporting scheme of last resort. Only use them if alternative options are demonstrably worse.

    For example, your code could be restructured to not use an exception at all
    Code:
    int main()
    {
       double val1, val2, result;
       val1 = val2 = result = 0;
        
       cout << "Please enter two values separated by spaces:\n";
       while(cin >> val1 >> val2)
       {
           if(val2 == 0)
           {       
                   cout << "Error: Second value must be non-zero\n";
                          << "\nTry again? Enter y or n" << endl;
                   char c;
                   cin >> c;
                    if(!cin || c == 'n')
                        break;     
            }
            else
            {    
                 result = val1 / val2;
                 cout << "Result: " << result << endl;
             }
       }                   
       return 0;
    }
    I'd possibly restructure it further to be even simpler than that, and better handle I/O errors on cin, but you get the idea.
    thames and iMalc like this.
    Right 98% of the time, and don't care about the other 3%.

  7. #7
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,258
    Yes, it is wrong in the given context.

    Don't get me wrong! There is absolutely nothing wrong with building a function to validate input and using exceptions to signal an error condition within that function. There is absolutely nothing wrong to transform a condition into an exception for the handling of errors when multiple paths may yield the same or similar errors requiring the same handling. (Actually, this second example is a perfect use of exceptions.)

    However, here you are transforming a simple condition into an exception only to toss it to yourself locally for immediate processing. You are actually complicating logic because of these pointless steps.

    Code:
    if(val2)
    {
        // do division
    }
    else
    {
        // report error
    }
    That example is significantly clearer.

    If you add multiple values, things start to change almost immediately (confirming the validity of two values) leaning heavily towards using exceptions because the fail branch for every validity test can be isolated into a single part of the function.

    [Edit]
    To be clear, your logic of confirming the validity of input should usually be part of the input process in any event making the use of exceptions pointless even for a lot of values.
    [/Edit]

    Using exceptions properly is a balancing act; don't let anybody tell you different.

    Soma
    thames and iMalc like this.

  8. #8
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,604
    Quote Originally Posted by grumpy View Post
    Not wrong, but certainly not recommended.

    Exceptions are generally intended for reporting an error that can't be handled by the code that detects the error. The cost of exceptions depends on quality of implementation of your compiler but, as a rule of thumb, probably cost more than is justifiable if any alternative options are available.

    In other words, view exceptions as an error reporting scheme of last resort. Only use them if alternative options are demonstrably worse.

    For example, your code could be restructured to not use an exception at allI'd possibly restructure it further to be even simpler than that, and better handle I/O errors on cin, but you get the idea.
    I would rewrite the code as
    Code:
    int main()
    {
       double val1, val2, result;
       val1 = val2 = result = 0;
         
       cout << "Please enter two values separated by spaces:\n";
       while(cin >> val1 >> val2)
       {
           if(val2 == 0)
           {      
                   cout << "Error: Second value must be non-zero\n";
                          << "\nTry again? Enter y or n" << endl;
                   char c;
                   cin >> c;
                    if(!cin || c == 'n')
                        break;
                   continue;    
            }
            result = val1 / val2;
            cout << "Result: " << result << endl;
       }                  
       return 0;
    }
    Since otherwise you will essentially have Microsoft code where you have extremely nested if statements in a row if you have many conditions to check (never a good thing).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. try & catch
    By kawafis44 in forum C++ Programming
    Replies: 5
    Last Post: 11-02-2008, 03:04 PM
  2. What can be done with catch(...)?
    By 6tr6tr in forum C++ Programming
    Replies: 6
    Last Post: 04-17-2008, 10:27 AM
  3. Is there a catch to return in a try/catch box?
    By meili100 in forum C++ Programming
    Replies: 25
    Last Post: 11-21-2007, 12:33 PM
  4. how can I use try catch?
    By Tonyukuk in forum C# Programming
    Replies: 1
    Last Post: 05-09-2003, 12:02 AM
  5. try ... catch
    By monkeymon in forum Windows Programming
    Replies: 5
    Last Post: 05-24-2002, 03:06 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21