Error handling with return codes · Gestion des erreurs avec codes de retour
C has no try/except
- Some languages throw exceptions when something goes wrong. C does not have exceptions.
- Instead, a C function reports trouble through its return value — a status code.
- The caller checks that code after every call and decides what to do.
C n'a pas de try/except
- Certains langages lancent des exceptions quand quelque chose tourne mal. C n'a pas d'exceptions.
- Au lieu de cela, une fonction C signale un problème via sa valeur de retour — un code de statut.
- L'appelant vérifie ce code après chaque appel et décide de ce qu'il faut faire.
Return a status code
- A common rule: return
0for success and a negative number like-1for failure. - So
int do_thing(...)returns0when it worked,-1when it could not. - The real "answer" is then handed back a different way (see the next step).
Retourner un code de statut
- Une règle courante : retourner
0pour le succès et un nombre négatif comme-1pour l'échec. - Donc
int do_thing(...)retourne0quand c'est réussi,-1quand c'est impossible. - La vraie "réponse" est alors rendue différemment (voir l'étape suivante).
Reporting the answer through an out-pointer
- If the return value is a status code, where does the real result go? Through an out-pointer.
- The caller passes the address of a variable; the function writes the answer with
*. - On failure, the function returns
-1and simply leaves that variable alone.
Signaler la réponse via un out-pointer
- Si la valeur de retour est un code de statut, où va le vrai résultat ? Via un out-pointer.
- L'appelant passe l'adresse d'une variable ; la fonction écrit la réponse dans
*. - En cas d'échec, la fonction retourne
-1et laisse simplement cette variable inchangée.
Sentinels for "no value"
- A sentinel is a special value that means "nothing here":
-1for an index,NULLfor a pointer. - Functions use sentinels so the caller can tell success from failure with a simple check.
- Always check for the sentinel before you trust the result.
Sentinelles pour "aucune valeur"
- Une sentinelle est une valeur spéciale signifiant "rien ici" :
-1pour un index,NULLpour un pointeur. - Les fonctions utilisent des sentinelles afin que l'appelant puisse distinguer le succès de l'échec avec une simple vérification.
- Vérifiez toujours la présence de la sentinelle avant de faire confiance au résultat.
#include <stdio.h>
int safe_div(int a, int b, int *result) {
if (b == 0) return -1; // failure: cannot divide by zero
*result = a / b; // success: hand back the answer
return 0;
}
int main(void) {
int r;
if (safe_div(10, 2, &r) == 0) {
printf("%d\n", r); // 5
}
return 0;
}
Common mistakes
- Return a non-zero code from
mainto signal an error. - Check the return value of any function that can fail.
Erreurs courantes
- Retournez un code non nul à partir de
mainpour signaler une erreur. - Vérifiez la valeur de retour de toute fonction susceptible d'échouer.
Now you try
- Return
0on success and-1on failure, and write the real answer through the out-pointer. - On failure, do not touch the out-pointer. Do not write a
main— the checker provides one.
À vous maintenant
- Retournez
0en cas de succès et-1en cas d'échec, et écrivez la vraie réponse via le pointeur de sortie. - En cas d'échec, ne touchez pas au pointeur de sortie. N'écrivez pas de
main— le vérificateur en fournit un.
Complete int safe_div(int a, int b, int *result): if b is 0, return -1 and leave *result alone. Otherwise store a / b in *result and return 0. Do not · non write a main. · Complétez int safe_div(int a, int b, int *result) : si b est 0, retournez -1 et laissez *result tel quel. Sinon stockez a / b dans *result et retournez 0. Ne pas écrire de main.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Complete int parse_int(const char *s, int *out): if s is a valid integer (digits, with an optional leading -), store its value in *out and return 0; otherwise return -1. Do not · non write a main. · Complétez int parse_int(const char *s, int *out) : si s est un entier valide (chiffres, avec un préfixe optionnel -), stockez sa valeur dans *out et retournez 0 ; sinon retournez -1. Ne pas écrire de main.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Complete int withdraw(int balance, int amount, int *new_balance): if amount is more than balance, return -1. Otherwise set *new_balance to · à balance - amount and return 0. Do not · non write a main. · Complétez int withdraw(int balance, int amount, int *new_balance) : si amount est supérieur à balance, retournez -1. Sinon définissez *new_balance à balance - amount et retournez 0. Ne pas écrire de main.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.