forked from benoitlecallennec-hes/template_slides_course
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08_Exceptions.html
More file actions
563 lines (497 loc) · 21.1 KB
/
Copy path08_Exceptions.html
File metadata and controls
563 lines (497 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>HE-Arc - 1242.2 Langage C++ - Chapitre 8 - Les exceptions</title>
<link rel="stylesheet" href="dist/reset.css">
<link rel="stylesheet" href="dist/reveal.css">
<link rel="stylesheet" href="dist/theme/hearc.css" id="theme">
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<link rel="shortcut icon" href="https://www.he-arc.ch/wp-content/uploads/2021/12/cropped-hearc-icon-192x192.png"
type="image/vnd.microsoft.icon" />
<!-- Theme used for syntax highlighted code -->
<link rel="stylesheet" href="plugin/highlight/vs.css" id="highlight-theme">
</head>
<body>
<img id="logo-hearc" src="./medias/logo_he-arc.png" alt="Logo HE-ARC">
<img id="logo-hesso" src="./medias/logo_hes-so.png" alt="Logo HES-SO">
<p id="course-infos">1242.2 Langage C++ - 2025-2026</p>
<div class="reveal">
<div class="slides">
<!---------- TITLE ---------->
<section>
<h1>
Chapitre 8
</h1>
<h2>
Les exceptions
</h2>
<div class="container">
<div class="col-left">
<p>1. Gestion des erreurs</p>
<p>2. Principe des exceptions</p>
<p>3. <inline-code><highlight>try</highlight></inline-code>, <inline-code><highlight>catch</highlight></inline-code> et <inline-code><highlight>throw</highlight></inline-code></p>
</div>
<div class="col-right">
<p>4. Relance d'exceptions</p>
<p>5. <inline-code><highlight>noexcept</highlight></inline-code></p>
<p>6. <inline-code><highlight>std::exception</highlight></inline-code> et <inline-code><highlight>what()</highlight></inline-code></p>
</p>
</div>
</div>
</section>
<!---------- 1. Gestion des erreurs ---------->
<section>
<section>
<h2>8.1 Gestion des erreurs en C++</h2>
<h3>Méthode historique</h3>
<div class="container">
<div class="col-left">
<pre style="width: 800;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="3, 7-8">
// f(x) = x^2, for x > 0
// Else, returns an error code
#define ERROR_CODE -1
int f(int x)
{
if (x <= 0)
return ERROR_CODE;
return x*x;
}
</code></pre>
</div>
<div class="col-right">
<pre style="width: 1200;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="7-10">
int main()
{
int x = 0;
int result = ERROR_CODE;
std::cin >> x;
result = f(x);
if (result == ERROR_CODE)
std::println("Error");
else
std::println(result);
return 0;
}
</code></pre>
</div>
</div>
</section>
<section>
<h2>8.1 Gestion des erreurs en C++</h2>
<h3>Inconvénients</h3>
<p>Code de gestion d'erreurs mélangé au "vrai" code</p>
<p>L'appelant doit savoir ce que signifient les codes d'erreurs retournés</p>
<p>Retourner une valeur et un code d'erreur en même temps</p>
</section>
<section>
<h2>8.1 Gestion des erreurs en C++</h2>
<h3>Les exceptions</h3>
<div class="container">
<div class="col-left">
<pre style="width: 700;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.6em;"
data-line-numbers="8">
// f(x) = x^2, for x > 0
// Else, throws an exception
#define ERROR_CODE -1
int f(int x)
{
if (x <= 0)
throw ERROR_CODE;
return x*x;
}
</code></pre>
<p><inline-code><highlight>throw</highlight></inline-code> : lance une exception</p>
<p><inline-code><highlight>catch</highlight></inline-code> : attrape une exception</p>
</div>
<div class="col-right">
<pre style="width: 1200;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.5em;"
data-line-numbers="6-13">
int main()
{
int x = 0;
int result = -1;
std::cin >> x;
try
{
result = f(x);
}
catch (...)
{
std::println("Error caught");
}
std::println("result: {}", result);
}
</code></pre>
</div>
</div>
</section>
</section>
<!---------- 2. Principe des exceptions ---------->
<section>
<section>
<h2>8.2 Principe des exceptions</h2>
<p>Lors de la détection d'une «erreur» (fonctionnement imprévu)</p>
<p><highlight>Exception</highlight> : signal logiciel, accompagné de données (int, string, ..., objet).
Une exception est souvent un objet de la classe <inline-code><highlight>std::exception</highlight></inline-code> ou d'une classe dérivée</p>
<p>Lorsqu'une exception est lancée (avec <inline-code><highlight>throw</highlight></inline-code>), le traitement en cours est <highlight>interrompu</highlight></p>
<p>L'exception remonte les fonctions appelantes jusqu'à être attrapée (avec <inline-code><highlight>catch</highlight></inline-code>)</p>
<p>Si elle n'est pas attrapée, alors le programme se termine</p>
<br>
<h3>Avantages</h3>
<p>Les exceptions permettent de séparer le traitement d'erreur du reste du code</p>
</section>
<section>
<h2>8.2 Syntaxe de la gestion de exceptions</h2>
<p>Les instructions pouvant lever une exception doivent être à l'intérieur d'un bloc :</p>
<p><inline-code><highlight>try { /*instructions*/ }</highlight></inline-code></p>
<br>
<p>Un bloc <inline-code><highlight>try</highlight></inline-code> doit être immédiatement suivi d'au moins un bloc de gestion d'erreur :</p>
<p><inline-code><highlight>catch () { /*instructions*/ }</highlight></inline-code></p>
<br>
<p>Une exception est levée par l'instruction :</p>
<p><inline-code><highlight>throw</highlight></inline-code></p>
</section>
<section>
<h2>8.2 Exemple simple</h2>
<pre style="width: 800;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
int main()
{
auto diviseur = 0;
<b>try</b>
{
if (diviseur == 0) <b>throw diviseur;</b>
std::println("Q: {}", dividende/diviseur);
}
<b>catch (int &d)</b> // Exception handler for int
{
std::println("Division par {}", d);
}
<b>catch (...)</b> // Exception handler for all other types
{
std::println("Another error");
}
return 0;
}
</code></pre>
</section>
<section>
<h2>8.2 Exemple simple</h2>
<p>Le premier gestionnaire compatible avec le type de l'exception l'attrape</p>
<p>Au plus un gestionnaire est exécuté pour une exception levée</p>
<p>Donc, si plusieurs gestionnaires sont appropriés pour le type de l'exception, seul le premier sera exécuté</p>
<p>Il convient donc de commencer par les gestionnaires les plus spécialisés, et terminer par le plus général</p>
</section>
</section>
<!---------- 3. Try catch throw ---------->
<section>
<section>
<h2>8.3 Le bloc <span style="text-transform: lowercase;"><inline-code><highlight>try</highlight></inline-code></span></h2>
<p>Pour être gérable, une exception doit être levée dans un bloc <inline-code><highlight>try</highlight></inline-code></p>
<div class="container">
<div class="col-left">
<pre style="width: 700px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
try
{
throw "err!";
}
</code>
</pre>
</div>
<div class="col-right">
<pre style="width: 700px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
void foo()
{
throw ERROR_CODE_27;
}
try
{
foo();
}
</code></pre>
</div>
</div>
<p>Si l'instruction <inline-code><highlight>throw</highlight></inline-code> n'est pas dans un bloc <inline-code><highlight>try</highlight></inline-code>, la levée de l'exception entraine la fin du programme ⇒ <inline-code><highlight>terminate()</highlight></inline-code></p>
<p><warning>⚠️ Attention :</warning> <inline-code><highlight>throw</highlight></inline-code> n'apparait pas toujours explicitement dans le code. Exemple avec l'opérateur <inline-code><highlight>new</highlight></inline-code></p>
</section>
<section>
<h2>8.3 Le bloc <span style="text-transform: lowercase;"><inline-code><highlight>catch</highlight></inline-code></span></h2>
<p>Un bloc <inline-code><highlight>try</highlight></inline-code> doit être immédiatement suivi par au moins un gestionnaire <inline-code><highlight>catch</highlight></inline-code></p>
<pre style="width: 1800px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
try {
// Instructions
}
catch (int except1) { // Handle int exceptions
// Instructions
}
catch (std::string except2) { // Handle string exceptions
// Instructions
}
catch (std::exception &except3) { // Handle std::exception exceptions
// Instructions
}
catch (...) { // Handle all other exceptions
// Instructions
}
</code></pre>
</section>
<section>
<h2>8.3 Le mot-clef <span style="text-transform: lowercase;"><inline-code><highlight>throw</highlight></inline-code></span></h2>
<p><inline-code><highlight>throw</highlight></inline-code> peut envoyer des messages de n'importe quel type, y compris des objets</p>
<pre style="width: 1400px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
// NOTE: no need for breaks here
try {
switch(i) {
case 1: throw 2;
case 2: throw "Error!";
case 3: throw objet;
}
}
catch(int x) {
std::println("Integer exception: {}", x);
}
catch(const char* str) {
std::println("String exception: {}", str);
}
catch(Classe &obj) {
std::println("Object exception: {}", obj.print());
}
</code></pre>
</section>
<section>
<h2>8.3 Gestionnaires d'exceptions</h2>
<p>Lorsqu'une exception de type <inline-code>T</inline-code> est levée, le compilateur cherche un gestionnaire :</p>
<p>1. de type <inline-code><highlight>T</highlight></inline-code></p>
<p>2. de superclasse de <inline-code><highlight>T</highlight></inline-code></p>
<p>3. pointeur sur une classe dérivée</p>
<p>4. type indéterminé : <inline-code><highlight>catch(...)</highlight></inline-code> (à placer en dernier)</p>
<br>
<p>Si l'exception est levée dans une fonction, le compilateur cherche un gestionnaire dans la fonction. Si ce n'est pas le cas, dans la fonction appelante, etc.</p>
<p>Le gestionnaire peut mettre fin au programme. Si ce n'est pas le cas, l'exécution continue par l'instruction qui suit les gestionnaires : <highlight>la fin du bloc try n'est pas exécutée.</highlight></p>
<p>Si aucun gestionnaire n'est trouvé, il appelle la fonction <inline-code><highlight>terminate()</highlight></inline-code>. Par défaut, celle-ci appelle <inline-code><highlight>abort()</highlight></inline-code></p>
</section>
<section>
<h2>🌶️ 8.3 Déclaration et problématique</h2>
<p>Le principal problème lié aux exceptions est la libération des ressources :</p>
<p>- Libérer les ressources allouées dynamiquement</p>
<p>- Fermer les flux</p>
<br>
<h3>Solutions</h3>
<p>1. Les allocateurs</p>
<p>2. RAII (Resource Acquisition Is Initialization)</p>
</section>
</section>
<!---------- 4. Relance d'exceptions ---------->
<section>
<section>
<h2>8.4 Relance d'exceptions</h2>
<p>Il est possible de relancer une exception déjà lancée</p>
<p>Il faut utiliser l'instruction <inline-code><highlight>throw</highlight></inline-code> sans argument</p>
<div class="container">
<div class="col-left">
<pre style="width: 900px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
void foo()
{
try {
int n=2;
throw n;
}
catch(int) {
std::println("Caught in foo");
throw;
}
}
</code>
</pre>
</div>
<div class="col-right">
<pre style="width: 900px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
int main()
{
try {
foo();
}
catch(int) {
std::println("Caught in main");
// Now end the program
}
return 0;
}
</code></pre>
</div>
</div>
</section>
</section>
<!---------- 5. noexcept ---------->
<section>
<section>
<h2>8.5 <span style="text-transform: lowercase;"><inline-code><highlight>noexcept</highlight></inline-code></span></h2>
<p>Le mot clé <inline-code><highlight>noexcept</highlight></inline-code> indique que la fonction ne doit pas lever d'exception</p>
<p>Il est possible de spécifier une condition pour lever une exception</p>
<pre style="width: 1500px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 2em;"
data-line-numbers="">
// Do not throw an exception
void f1() noexcept(true) { ... }
// Might throw an exception
void f2() noexcept(false) { ... }
// Might throw an exception if expr is false
void f3() noexcept(expr) { ... }
// Might throw an exception if foo() may throw too
void f4() noexcept(noexcept(foo())) { ... }
</code></pre>
<inline-code><highlight>noexcept</highlight></inline-code> est un contrat : si une exception est levée, la fonction <inline-code><highlight>std::terminate()</highlight></inline-code> est appelée</p>
</section>
</section>
<!---------- 6. std::exception et what() ---------->
<section>
<section>
<h2>8.6 Les classes exceptions standards</h2>
<p>La bibliothèque standard définit des classes exceptions</p>
<p>Leur superclasse commune est <inline-code><highlight>std::exception</highlight></inline-code></p>
<p>Elle est définie dans le fichier d'en-tête <inline-code><highlight>stdexcept</highlight></inline-code></p>
<p>Elle comporte une méthode <inline-code><highlight>what()</highlight></inline-code> retournant une chaîne de caractères</p>
<p>Les exceptions personnalisées hériteront donc de <inline-code><highlight>std::exception</highlight></inline-code> et la méthode <inline-code><highlight>what()</highlight></inline-code> sera redéfinie.</p>
<p>Double intérêt :</p>
<p>1. Transmettre des informations (attributs, what())</p>
<p>2. catch (const exception &e) plutôt que catch(...)</p>
<p><success>✅ Bonne pratique :</success> lancer les exceptions par valeur, et les attraper par référence</p>
<p><a href="https://en.cppreference.com/w/cpp/error/exception">📚 Exceptions (cppreference)</a></p>
</section>
<section>
<h2>8.6 Spécialisation de la classe <span style="text-transform: lowercase;"><inline-code><highlight>std::exception</highlight></inline-code></span></h2>
<pre style="width: 1500px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.8em;"
data-line-numbers="">
#include <print>
#include <stdexcept> // or #include <exception>
class Exception1 : public std::exception {
public:
Exception1() noexcept {}
const char* what() const noexcept override {
return "exception1";
}
};
class Exception2 : public std::exception {
public:
Exception2() noexcept {}
const char* what() const noexcept override {
return "exception2";
}
};
</code></pre>
</section>
<section>
<h2>8.6 Surcharge de <span style="text-transform: lowercase;"><inline-code><highlight>what()</highlight></inline-code></span></h2>
<pre style="width: 1500px;"><code
class="c++"
data-trim
data-noescape
style="font-size: 1.7em;"
data-line-numbers="">
int main()
{
try {
std::println("block try 1");
throw Exception1();
}
catch(const Exception1 &e) {
std::println("Caught Exception1: {}", e.what());
}
try {
std::println("block try 2");
throw Exception2();
}
catch (const std::exception &e) {
std::println("Caught exception: {}", e.what());
}
return 0;
}
</code></pre>
<p><warning>⚠️ Attention :</warning> une référence est nécessaire pour le polymorphisme</p>
</section>
</section>
</div>
</div>
<!---------- CONTENT ---------->
<script src="dist/reveal.js"></script>
<script src="plugin/notes/notes.js"></script>
<script src="plugin/markdown/markdown.js"></script>
<script src="plugin/highlight/highlight.js"></script>
<script>
// More info about initialization & config:
// - https://revealjs.com/initialization/
// - https://revealjs.com/config/
Reveal.initialize({
hash: true,
width: 1920,
height: 1080,
transition: "none",
center: false,
slideNumber: 'c/t',
// Learn about plugins: https://revealjs.com/plugins/
plugins: [RevealMarkdown, RevealHighlight, RevealNotes]
});
</script>
</body>
</html>