简体   繁体   中英

Exceptions in C (Try Catch)

I'm just asking how to use Try Catch in C. I was searching at Google and I found that C does not support Exceptions but I can use something call setjmp and longjmp, but I did not understand that. Also, I know how to use exceptions in C++. It'd be something like this:

#include <iostream>

using namespace std;

main(){
   int opc;
   bool aux=true;
   cin.exceptions(std::istream::failbit);
   do{
   try{
       cout<<"PLEASE INSERT VALUE:"<<endl;
       cin>>opc;
       aux=true;

   }
   catch(std::ios_base::failure& fail){
             aux=false;
             cout<<"PLEASE INSERT A VALID VALUE."<<endl;
             cin.clear();
             std::string tmp;
             getline(cin, tmp);
           }
           }while(aux==false);
 system("PAUSE");
}//main

Any help with C?

There is no such thing in C .
As a workaround you may want to:

  • Put the code under try in a function
  • Make the function return an error code
  • Analyze the returned code and put what you would have done in catch under a condition

Example:

int error = my_try();
if(error == ENOMEM)
{
    printf("Out of memory: Abort\n");
    return -1;
}
else if(error == EINVAL)
{
    printf("Invalid parameter\n");
    return -1;
}
// else error == 0: everything went smoothly

Since C doesn't support automatic exceptions best practice is to check the return value from any function that may fail. And yes, you usually get to write a lot of error handling code when writing robust programs.

The functions setjmp / longjmp is support for manual exceptions (similar to throw in java) and can be used to reduce the amount of checking necessary.

So, what do I mean when I say that there are no automatic exceptions? When things go terribly wrong in C the process gets a signal, not an exception. So there are automatic exceptions, only the mechanism is totally different.

This means that in C you still need to check return values from functions like malloc , because setjmp / longjmp won't protect you from the effects of invoking undefined behaviour (like using a null pointer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM