Thread: Exceptions in C

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    7

    Exclamation Exceptions in C

    Hi
    Is there a possiblity of handling exceptions in C as in Java and C++, Of course Error handling not based on the retuntype of the function, Exception should handle runtime error like divide by zero etc.

    Is that possible????

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    C is really more a build- it- yourself language.

    Exception handling really means what you decide to do when errors occur.
    For instance, let's say a user inputs a zero to calculate. Now if you didn't want the program to abort you could check for equivelance with zero first, and if so print a "bad val" message and then re-prompt the user for input. You could even print and save in an error log which lists the timeof day, error code etc. This is an example of do-it-yourself error handling.
    So no I don't think C has any built-in error handling.
    oh What is wrong with using the return value of a function? How hard is
    if(bad_val){ ...?
    if(!devide(your_num)){ ...?

    I don't think it's a matter of inadaquacy of return value exception handling per se that's all.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You can implement your own, or use someone elses.
    here is one I quickly found (of several)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,868
    For basic exception handling in C use __try() and __except()

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > For basic exception handling in C use __try() and __except()
    Which would be compiler specific.....
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User wavering's Avatar
    Join Date
    Dec 2001
    Posts
    26
    This has solved a problem for me, many thanks. I need to carry on if my prog divides by zero and this works ... on MSVC++ compiler ( But I am writing in C - works on both C and C++)

    Code:
    #include <stdio.h>
    
    int test(){
      int j=100;
      int k=0;
      _try{
        j=j/k;  
      }
      _except(puts("Do stuff here if you want ..."), 1){
        puts("ERROR was found but no problem ...");
        return(0);
      }
      puts("If no error you will come here ...");
      return(1);
    }
    
    void main(){
      int dummy;
      dummy=test();
      printf("Return %d\n",dummy);
    }

  7. #7
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    I agree with Sebastiani that you can create your own error handling, which isn't very hard to do. You just have to code very carefully.

    Personally I think it's very valuable gaining experience in writing safe and robust code.

  8. #8
    Registered User wavering's Avatar
    Join Date
    Dec 2001
    Posts
    26
    Thanks Shiro

    I take your point but what I was trying to do was avoid a situation where I have to test for all sorts of possible conditions, thereby slowing my ( time critical ) program down. I thought ( naively ) that _try/_except would solve the time problem. Actually it does the job but is no faster than before. Interesting though ...

    I guess experience is just that - you keep trying things. Some work - some don't. Must say that I can see why some people hate C and others love it. I am joining the ranks of the devotees because it allows you to get right up to the machinery ( especially if you are an asm fan as well ). To the non devotees it must be a pain in the rear ( "what's wrong with Basic and who the hell needs pointers anyway?" )

    I guess the test is whether you prefer to drive an automatic car or a manual gear change ( "stick shift" if you speak USA )

  9. #9
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Exceptions are no faster when they aren't thrown, and slower when they are as opposed to the standard error checking by the value returned.

    Where they are beneficial is in client code in which can handle multiple error conditions in the same block, in forcing a client to handle an error, rather than let the program continue onto the real of interminate (and often erratic) behavior because an error was not handled, and in the few cases were all possible outputs for a function are valid, but not all inputs are (thing about natural log, in which the output is all reals, but the input must be greater than 0).
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  10. #10
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    >I need to carry on if my prog divides by zero and this works

    Strange. If you'r program divides by zero, then from a mathematical point of view, j would have an undefined value. And so the behaviour of your program would become unpredictable.

    Personally I would prefer:

    Code:
    #include <stdio.h>
    
    int test () {
      int j=100;
      int k=0;
      int retval;
    
      if (k == 0)
      {
        printf ("ERROR: division by zero\n");
        retval = ERROR_DIVISION_BY_ZERO;
      else
      {
         j /= k;
         retval = NO_ERROR;
      }
    
      return retval;
    }  
    
    int main(){
      int dummy;
      dummy= test ();
      
      if (dummy != NO_ERROR)
      {
        /* An error occurred, handle this error */
      }
    
      printf("Return %d\n",dummy);
      return 0;
    }
    I have a question. Assume that a division by zero occurs, what value will j then have when using _try and _except? And what will be the consequences of using j in functions to come?

  11. #11
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    >Assume that a division by zero occurs, what value will j then have when using _try and _except?

    j retains its original value of 100.

  12. #12
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    >j retains its original value of 100.

    I see. And so this will lead to incorrect behaviour of the software, I will never use this kind of error handling. :-)

  13. #13
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    >And so this will lead to incorrect behaviour of the software

    I think this is why an exception would be thrown. If you want to try and produce the correct behavior you can alter the value when handling the exception.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Debug --> Exceptions in Visual Studio 2005
    By George2 in forum C# Programming
    Replies: 1
    Last Post: 08-10-2007, 02:12 AM
  2. Exceptions and constructors
    By Mostly Harmless in forum C++ Programming
    Replies: 2
    Last Post: 06-12-2007, 11:20 AM
  3. Long-lasting objects that throw exceptions
    By drrngrvy in forum C++ Programming
    Replies: 7
    Last Post: 10-05-2006, 04:30 PM
  4. Need advice: catch exceptions or call methods to check bits?
    By registering in forum C++ Programming
    Replies: 1
    Last Post: 10-03-2003, 01:49 PM
  5. Throwing exceptions with constructors
    By nickname_changed in forum C++ Programming
    Replies: 14
    Last Post: 07-08-2003, 09:21 AM