Exception handling · Gestion des exceptions
| English | Français |
|---|---|
| exception/ekˈsepʃn/ | exception |
| exception handling/ekˈsepʃn ˈhændlɪŋ/ | gestion des exceptions |
| raise/reɪz/ | augmentent |
The check that cannot be written
- A program opens a file. Before opening it, you could check that the file exists, that it is readable, that the disk is present. Suppose every check passes.
- Between the last check and the open, a user pulls out the USB stick. The file existed when you asked and does not exist when you open it, and no amount of checking in advance could have closed that gap.
- Some errors are simply not preventable, because the world changes between the test and the action. What a program can do is respond to them when they happen.
- This lesson is the exception 异常, the TRY structure that handles one, and where in a program an exception should be caught.
Le contrôle qui ne peut pas s'écrire
- Un programme ouvre un fichier. Avant de l'ouvrir, vous pourriez vérifier que le fichier existe, qu'il est lisible, que le disque est présent. Supposons que tous les contrôles passent.
- Entre le dernier contrôle et l'ouverture, un utilisateur retire la clé USB. Le fichier existait quand vous avez demandé et n'existe pas quand vous l'ouvrez, et aucun nombre de contrôles à l'avance n'aurait pu combler cet écart.
- Certaines erreurs sont simplement imprévisibles, car le monde change entre le test et l'action. Ce qu'un programme peut faire, c'est réagir à elles lorsqu'elles surviennent.
- Cette leçon porte sur l'exception 异常, la structure TRY qui gère une exception, et où dans un programme une exception devrait être capturée.
What an exception is and why handle it
- An exception is an error that occurs during execution: division by zero, a file not found, invalid input, a network that has gone away.
- Exception handling 异常处理 lets the program detect the error and respond in a controlled way, instead of crashing and losing the user's work.
- Real programs face errors that cannot be prevented in advance, as the hook shows. And without exceptions, every single operation would need its own
IFcheck around it, burying the actual algorithm in error tests. - The third benefit is the one the exam most often asks for: it separates the normal flow from the error handling, so the main path reads cleanly.
Qu'est-ce qu'une exception et pourquoi la gérer
- Une exception est une erreur qui survient pendant l'exécution : division par zéro, fichier non trouvé, entrée invalide, réseau disparu.
- La gestion des exceptions 异常处理 permet au programme de détecter l'erreur et de répondre de manière contrôlée, au lieu de planter et de perdre le travail de l'utilisateur.
- Les vrais programmes font face à des erreurs qui ne peuvent pas être empêchées à l'avance, comme le montre le crochet. Et sans exceptions, chaque opération nécessiterait sa propre
IFvérification autour d'elle, enfouissant l'algorithme réel dans des tests d'erreur. - Le troisième avantage est celui que l'examen demande le plus souvent : cela sépare le flux normal de la gestion des erreurs, de sorte que le chemin principal reste propre.
An exception is: · Une exception est :
Exceptions are run-time problems (divide by zero, file not found) that handling lets you respond to gracefully. · Les exceptions sont des problèmes de temps d'exécution (division par zéro, fichier non trouvé) dont la gestion permet de répondre avec grâce.
Why use exception handling rather than checking for every error in advance? Select all · tout that apply. · Pourquoi utiliser la gestion des exceptions plutôt que de vérifier chaque erreur à l'avance ? Sélectionnez toutes les réponses applicables.
The benefits are correctness and clarity. Speed is not one of them; handling adds a little overhead, which is worth paying. · Les avantages sont la justesse et la clarté. La vitesse n'est pas l'un d'eux ; la gestion ajoute un léger surcoût, ce qui vaut le coût payé.
The TRY structure
- The TRY block holds the code that might fail. If it runs without error, the EXCEPT blocks are skipped entirely.
- If an exception occurs, execution jumps immediately to the first matching EXCEPT block. The rest of the TRY block does not run.
- A FINALLY block runs whether or not an exception happened, which makes it the right place for cleanup such as closing a file.
One path when all is well, another when it is not, and one that always runs
La structure TRY
TRY
OPENFILE "data.txt" FOR READ
READFILE "data.txt", line
CLOSEFILE "data.txt"
EXCEPT FileNotFound
OUTPUT "Sorry, the file does not exist."
EXCEPT ReadError
OUTPUT "Sorry, there was an error reading the file."
FINALLY
OUTPUT "Finished attempting to read."
ENDTRY
- Le bloc TRY contient le code qui pourrait échouer. S'il s'exécute sans erreur, les blocs EXCEPT sont totalement ignorés.
- Si une exception se produit, l'exécution saute immédiatement vers le bloc EXCEPT correspondant premier. Le reste du bloc TRY ne s'exécute pas.
- Un bloc FINALLY s'exécute que ce soit ou non qu'une exception se soit produite, ce qui en fait le bon endroit pour la cleanup comme fermer un fichier.

Un seul chemin quand tout va bien, un autre quand ce n'est pas le cas, et un qui s'exécute toujours
How exception handling flows · Comment la gestion des exceptions s'écoule
Step through what happens when code fails. The exception jumps out of the normal flow to a handler, FINALLY cleans up either way, and the program carries on instead of crashing. · Passez en revue ce qui se passe quand le code échoue. L'exception saute hors du flux normal vers un handler, FINALLY nettoie des deux côtés, et le programme continue au lieu de planter.
Match each exception-handling keyword to its job. · Associez chaque mot-clé de gestion des exceptions à sa fonction.
TRY guards the risky code, EXCEPT catches, FINALLY cleans up either way, RAISE throws an error to be caught. · TRY protège le code risqué, EXCEPT capture, FINALLY nettoie des deux côtés, RAISE lève une erreur pour être capturée.
A FINALLY block: · Un bloc FINALLY :
FINALLY always runs, making it ideal for cleanup such as closing files. · FINALLY s'exécute toujours, ce qui le rend idéal pour le nettoyage comme la fermeture des fichiers.
The block that runs whether or not an exception occurred, making it right for closing files, is ____. · Le bloc qui s'exécute qu'il y ait eu une exception ou non, ce qui le rend adapté à la fermeture des fichiers, est ____.
Cleanup must happen on both paths. Putting CLOSEFILE only in the TRY block means it is skipped exactly when an error left the file open. · Le nettoyage doit se produire sur les deux chemins. Placer CLOSEFILE uniquement dans le bloc TRY signifie qu'il est sauté exactement quand une erreur a laissé le fichier ouvert.
Worked example: trace the flow
- In the code above, the file does not exist. State exactly what is output and what is skipped.
OPENFILEraises FileNotFound, so execution leaves the TRY block immediately: theREADFILEandCLOSEFILElines never run.- The
FileNotFoundEXCEPT block runs, outputting "Sorry, the file does not exist." TheReadErrorblock does not run, because only the first matching handler is used. - The FINALLY block runs, outputting "Finished attempting to read."
- The mark most often lost is noticing that the rest of the TRY block is abandoned.
Exemple résolu : tracer le flux
- Dans le code ci-dessus, le fichier n'existe pas. Indiquer exactement ce qui est affiché et ce qui est ignoré.
OPENFILElève FileNotFound, donc l'exécution quitte le bloc TRY immédiatement : les lignesREADFILEetCLOSEFILEne s'exécutent jamais.- Le bloc EXCEPT
FileNotFounds'exécute, affichant « Désolé, le fichier n'existe pas. » Le blocReadErrorne s'exécute pas, car seul le premier gestionnaire correspondant est utilisé. - Le bloc FINALLY s'exécute, affichant « Terminé en tentant de lire. »
- Le point le plus souvent perdu est de remarquer que le reste du bloc TRY est abandonné.
The file in the TRY block does not exist. Put what happens in order. · Le fichier dans le bloc TRY n'existe pas. Mettez ce qui se passe dans l'ordre.
Only the first matching handler runs, and FINALLY runs either way. The skipped remainder of the TRY block is the mark most often missed. · Seul le premier gestionnaire correspondant s'exécute, et FINALLY s'exécute dans tous les cas. Le reste ignoré du bloc TRY est le point le plus souvent manqué.
Raising an exception
- A subroutine that detects a problem it cannot sensibly deal with can raise 抛出 an exception, passing responsibility to whoever called it:
- This is the right design when the subroutine knows something is wrong but not what should be done about it. A division routine knows the divisor is zero; only the caller knows whether to ask the user again, use a default, or abandon the calculation.
Lever une exception
- Une sous-routine qui détecte un problème auquel elle ne peut raisonnablement remédier peut lever 抛出 une exception, transférant la responsabilité à qui l'a appelée :
IF b = 0 THEN RAISE DivideByZero
- C'est la bonne conception quand la sous-routine sait que quelque chose ne va pas mais pas quoi faire à propos. Une routine de division sait que le diviseur est zéro ; seul l'appelant sait s'il faut demander à l'utilisateur de réessayer, utiliser une valeur par défaut, ou abandonner le calcul.
A subroutine uses RAISE to: · Une sous-routine utilise RAISE pour :
RAISE throws an exception up to the caller, which can catch it with EXCEPT. · RAISE lance une exception au caller, qui peut la capturer avec EXCEPT.
Why would a division subroutine RAISE an exception instead of handling a zero divisor itself? · Pourquoi une sous-routine de division lèverait-elle une exception au lieu de gérer elle-même un diviseur zéro ?
Ask the user again, use a default, or abandon the calculation: only the calling code has the context to choose. · Demander à l'utilisateur de réessayer, utiliser une valeur par défaut, ou abandonner le calcul : seul le code appelant a le contexte pour choisir.
Where to handle it
- Handle an exception close to where it occurs when the response is simple and local: print a message, use a default, ask the user to try again.
- Handle it higher up when the decision belongs to a larger part of the program: whether to abandon a whole transaction, roll back a change, or tell the user the operation failed.
- The rule of thumb: catch it at the level that has enough information to decide what to do, not at the level that first notices.
Où la gérer
- Gérer une exception près de là où elle se produit quand la réponse est simple et locale : afficher un message, utiliser une valeur par défaut, demander à l'utilisateur de réessayer.
- La gérer plus haut quand la décision appartient à une plus grande partie du programme : s'abandonner une transaction entière, annuler un changement, ou informer l'utilisateur que l'opération a échoué.
- La règle empirique : la capturer au niveau qui a assez d'informations pour décider quoi faire, pas au niveau qui la remarque en premier.
Worked example: what not to do
- A student writes
EXCEPT: (do nothing)around a whole program so it never crashes. Explain why this is poor practice. - The exception is swallowed: the program continues as though nothing went wrong, so it carries on with missing or invalid data and produces wrong results instead of an obvious failure.
- A silent failure is harder to diagnose than a crash, because there is no message and no indication of where it happened.
- Catching every exception in one place also means the specific error type is lost, so no sensible response can be chosen. A handler should catch a specific exception and actually respond to it.
Exemple résolu : ce qu'il ne faut pas faire
- Un étudiant écrit
EXCEPT: (do nothing)autour de tout un programme pour qu'il ne plante jamais. Expliquer pourquoi c'est une mauvaise pratique. - L'exception est noyée : le programme continue comme si rien ne s'était passé, donc il poursuit avec des données manquantes ou invalides et produit de mauvais résultats au lieu d'un échec évident.
- Un échec silencieux est plus difficile à diagnostiquer qu'un crash, car il n'y a pas de message ni d'indication de là où il s'est produit.
- Attraper toutes les exceptions au même endroit signifie également que le type d'erreur spécifique est perdu, rendant impossible un choix de réponse approprié. Un gestionnaire devrait attraper une exception spécifique et y répondre effectivement.
Silently "swallowing" an exception (catching it but doing nothing) hides real errors and makes debugging hard — you should handle it or at least log it. · Avaler silencieusement une exception (la capturer mais ne rien faire) cache de vraies erreurs et rend le débogage difficile — il faut la gérer ou au moins la logger.
An empty handler hides the very problems you need to find; always respond or record the error. · Un gestionnaire vide masque les problèmes mêmes que vous devez trouver ; répondez toujours ou enregistrez l'erreur.
Marks that slip away
- When an exception occurs, the rest of the TRY block is skipped. Say so when tracing.
- Only the first matching EXCEPT runs, not all of them.
- FINALLY always runs, error or no error, which is what makes it right for closing files.
- Do not catch an exception and do nothing. A swallowed error is worse than a crash, because the program continues with bad data.
Pièges qui font perdre des points
- Lorsqu'une exception se produit, le reste du bloc TRY est ignoré. Mentionnez-le lors du traçage.
- Seul le premier EXCEPT correspondant s'exécute, pas tous.
- FINALLY s'exécute toujours, en cas d'erreur ou non, ce qui le rend idéal pour la fermeture des fichiers.
- Ne pas attraper une exception et ne rien faire. Une erreur étouffée est pire qu'un crash, car le programme continue avec des données incorrectes.
You've got it
- an exception is a run-time error; handling it lets a program respond instead of crashing, covers errors that cannot be prevented in advance, and separates normal code from error handling
- TRY holds the risky code; on an error the rest of it is skipped and the first matching EXCEPT runs; FINALLY runs either way, so cleanup belongs there
- a subroutine that cannot decide the response should RAISE the exception for its caller
- handle it close by for a simple local response, higher up when the decision needs a wider view; never catch it and do nothing
Vous avez compris
- une exception est une erreur d'exécution ; la gérer permet à un programme de réagir plutôt que de planter, couvre les erreurs qui ne peuvent pas être évitées à l'avance et sépare le code normal de la gestion des erreurs
- TRY contient le code risqué ; en cas d'erreur, le reste est ignoré et le premier EXCEPT correspondant s'exécute ; FINALLY s'exécute dans les deux cas, donc le nettoyage doit s'y faire
- une sous-routine qui ne peut pas décider de la réponse doit LÉVER l'exception pour son appelant
- la gérer près de là pour une réponse locale simple, plus haut lorsque la décision nécessite une vue d'ensemble plus large ; ne jamais l'attraper et ne rien faire