This repository has been archived by the owner on Dec 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
612 lines (592 loc) · 19.6 KB
/
index.html
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
<!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>Exception Handling</title>
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/league.css">
<!-- Theme used for syntax highlighting of code -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section><!--Intro-->
<h2>Exceptional Exception Handling</h2>
<p class=fragment>Hi I'm Derek</p>
</section>
<section class="stack"><!--Bio-->
<h2>Shameless Narcissism</h2>
<section>
<h2 class="fragment">I'm employed</h2>
<p class="fragment">I work at ____________.</p><!--Cylance Inc.-->
</section>
<section>
<h2>I'm got a fancy piece of paper.</h2>
<p class="fragment">I graduated from ____________.</p><!--Colorado State University-->
</section>
<section>
<h2>Three of my hobbies are:</h2>
<ul>
<li class="fragment">Performing ____________.</li><!--Magic-->
<li class="fragment">Playing ____________.</li><!--Board Games-->
<li class="fragment">Watching my favourite movies, ____________.</li><!--Star Wars-->
</ul>
</section>
<section>
<h2>Freebie</h2>
<p class="fragment">I like trivia.</p>
</section>
</section>
<section><!--Trivia 1-->
<h2>What was the first language to introduce exception handling?</h2>
<p class="fragment">LISP 1.5</p>
<aside class="notes">
<ul>
<li>Released in 1962</li>
<li>Used ERRSET keyword. returned NIL when there was an error.</li>
</ul>
</aside>
</section>
<section><!--Trivia 2-->
<h2>When were the Catch/Throw keywords first used?</h2>
<p class="fragment">1972</p>
<aside class="notes">
<ul>
<li>What we now call `finally` was introduced by the New Implementation of LISP (NIL) in mid 70's.</li>
<li>UNWIND-PROTECT</li>
</ul>
</aside>
</section>
<section><!--Trivia 3-->
<h2>When was the first paper on Structured Exception Handling Written?</h2>
<p class="fragment">1975</p>
<aside class="notes">
<p>Written by John Goodenough.</p>
</aside>
</section>
<section><!--Trivia 4-->
<h2>What are developers exceptionally bad at?</h2>
<p class="fragment">Exception Handling</p>
</section>
<section><!--Prevention-->
<h2>Prevention</h2>
<aside class="notes">
<p>The best way to handle exceptions is to never cause them.</p>
</aside>
</section>
<section class="stack"><!--Best Practice: Don't return or pass null-->
<h2>Don't Pass or Return Null Values</h2>
<section>
<p class="fragment">null, None, nil, undefined etc.</p>
</section>
<section><!--class SettlersOfCatan-->
<pre><code class="hljs lang-python">class SettlersOfCatan:
def can_build_at(self, x, y):
for player in self.players:
for settlement in self.settlements:
coords = settlement.location
if 2 < coords[0] - x or 2 < coords[1] - y:
return False
return True
def build_settlement(self x, y):
if self.can_build_at(x, y):
return Settlement(x, y)
return None
</code></pre>
</section>
<section><!--__main__-->
<pre><code class="hljs lang-python">if __name__ == '__main__':
game = SettlersOfCatan()
self.players.append(Player())
self.players(Player())
# Each player builds their first settlement
self.players[0].settlements.append(game.build_settlement(1, 2))
self.players[1].settlements.append(game.build_settlement(2, 3))
# Each player builds their second starting settlement
self.players[0].settlements.append(game.build_settlement(4, 7))
self.players[1].settlements.append(game.build_settlement(3, 3))
</code></pre>
</section>
<section><!--AttributeError Revealed-->
<pre><code class="hljs lang-bash">AttributeError: 'NoneType' object has no attribute 'location'</code></pre>
<pre class="fragment"><code class="hljs lang-python">
# The 2nd call to build_settlement() returns None. Since the
# result is not checked None gets added to the settlements.
self.players[1].settlements.append(game.build_settlement(2, 3))
# The subsequent call to build_settlement() raises the
# AttributeError when trying to get .location from None
def can_build_at(self, x, y):
for player.self.players:
for settlement in self.settlements:
coords = settlement.location
...
</code></pre>
</section>
<section>
<p>There is one more error though!</p>
</section>
<section><!--Nefarious score bug revealed-->
<pre><code class="hljs lang-python">if __name__ == '__main__':
game = SettlersOfCatan()
self.players.append(Player())
self.players.append(Player())
#build first settlements
self.players[1].settlements.append(game.build_settlement(1, 2))
self.players[1].settlements.append(game.build_settlement(2, 3))
for player in self.players:
print(player.score)
</code></pre>
</section>
<section><!--Class Player-->
<pre><code class="hljs lang-python">class Player:
@property
def score(self):
score = 0
if self.settlements is not None:
score += len(self.settlements)
if self.cities is not None:
score += len(self.cities)
if self.has_longest_road:
score += 2
if self.has_largest_army:
score += 2
return score
</code></pre>
</section>
<section><!--How to Fix it-->
<p>Throw/Raise an exception</p>
<pre><code class="hljs lang-python">def exceptional_build_settlement(self, x, y):
if self.cannot_build_at(x, y):
raise InvalidPlacementError(
f'(${x}, ${y}) is an invalid placement.'
)
return Settlement(x, y)
</code></pre>
</section>
<section><!--Magic reveal-->
<h1>MAGIC!</h1>
</section>
</section>
<section><!--Systemization-->
<h2>Systemization</h2><!--Maybe use Integration instead-->
<aside class="notes">
<p>Exceptional is a mindset not a single act. Follow the best practives everywhere.</p>
<p>At some point you'll have to deal with exceptions. This is how to deal with them.</p>
</aside>
</section>
<section class="stack"><!--Don't simply catch Exception-->
<h2>Don't catch Exception</h2>
<section>
<p class="fragment">unless you are catching a more specific exception first.</p>
</section>
<section><!--Example catching only exception-->
<pre><code class="hljs lang-cs">string cmdTxt = "SELECT Count(*) as MyCnt FROM MyTable";
SqlCommand cmd = new SqlCommand(cmdTxt, new SqlConnection());
try {
cmd.connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.read();
return Convert.ToInt32(reader["MyCnt"]);
}
catch (Exception e) {
ErrorHandler.sendEmailNotification(e);
}
</code></pre>
</section>
<section><!--Example catching better exceptions-->
<pre><code class="hljs lang-cs">string cmdTxt = "SELECT count(*) as MyCnt FROM MyTable";
SqlCommand cmd = new SqlCommand(cmdTxt, new SqlConnection());
try {
cmd.connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.read();
return Convert.ToInt32(reader["MyCnt"]);
} catch (InvalidOperationException sqle) {
return -1;
} catch (FormatException fe) {
return -1;
} catch (Exception e) {
ErrorHandler.sendEmailNotification(e);
}
</code></pre>
<aside class="notes">
<p>We can do better than just sending an email when an exception occurs.</p>
<p>Some errors we know could be resolved without code changes so return a usable but obviously incorrect value.</p>
</aside>
</section>
</section>
<section class="stack"><!--One line in the try block-->
<h2>Only include the protected line in a try block</h2>
<section>
<p class="fragment">Which line threw FormatException?</p>
<p class="fragment">Which threw InvalidOperationException?</p>
</section>
<section><!--Example with a single line in the try block-->
<pre><code class="hljs lang-cs">try{
cmd.connection.Open();
} catch (InvalidOperationException ioe) {
if (cmd.connection.State == ConnectionState.Broken) {
cmd.connection.close();
cmd.connection.open();
} else {
throw ioe;
}
...
}
</code></pre>
<aside class="notes">
<p>Now we know exactly how to handle an InvalidOperationException.</p>
<p>If the connection is broken it can be fixed simply by closing and reopening the connection.</p>
</aside>
</section>
</section>
<section class="stack"><!--Defer clean-up-->
<h2>Defer Clean-up for the finally block</h2>
<section>
<p class="fragment">Unmanaged resources should be closed regardless of a success or failure.</p>
</section>
<section><!--Example not using finally-->
<pre><code class="hljs lang-python">def write_config(path, content):
try:
config = open(path, 'wx+')
for line in content:
config.write(line)
config.close()
except FileExistsError as e:
logger.exception('Cannot overwrite existing config file')
</code></pre>
</section>
<section><!--Example using finally-->
<pre><code class="hljs lang-python">def write_config(path, content):
try:
config = open('path', 'wx+')
for line in content:
config.write(line)
except FileExistsError as e:
logger.exception('Cannot overwrite existing config file')
finally:
config.close()
</code></pre>
</section>
</section>
<section class="stack"><!--Use context-managers--><!--I'm debating this though cause they kinda silently swallow exceptions-->
<h2>Use Context Managers</h2>
<section>
<p class=fragment>The previous example can be even cleaner</p>
</section>
<section><!--Example using finally-->
<pre><code class="hljs lang-python">def write_config(path, content):
try:
config = open('path', 'wx+')
for line in content:
config.write(line)
except FileExistsError as e:
logger.exception('Cannot overwrite existing config file')
finally:
config.close()
</code></pre>
</section>
<section>
<pre><code class="hljs lang-python">def write_config(path, content):
with open(path, 'wx+') as config_f:
for line in content:
config_f.write(line);
</code></pre>
</section>
</section>
<section class="stack"><!--Heckendorn's Law-->
<h2>Heckendorn's Law</h2>
<section>
<p class="fragment">
"Thou shalt provide complete error messages." <br/>- Robert Heckendorn
</p>
</section>
<section><!--Example of static error message-->
<pre><code class="hljs lang-cs">class Celestial {}
class DeathStar : Celestial {}
class Moon : Celestial {}
public static bool isMoon(Celestial celestial) {
Type type = celestial.GetType();
if (type != typeof(Moon))
throw new ArgumentException("That's no Moon");
...
return true;
}
DeathStar deathstar = new DeathStar();
isMoon(deathstar);
</code></pre>
</section>
<section><!--Example of dynamic error message-->
<pre><code class="hljs lang-cs">class Celestial {}
class DeathStar : Celestial {}
class Moon : Celestial {}
public static bool isMoon(Celestial celestial) {
Type type = celestial.GetType();
if (type != typeof(Moon))
throw new ArgumentException($"A {type} is no Moon");
...
return true;
}
DeathStar deathstar = new DeathStar();
isMoon(deathstar);
</code></pre>
<aside class="notes">
<p>Instead of, "You do not have the permission for that action" say, "You do not have write permissions for `path` directory."</p>
</aside>
</section>
</section>
<section class="stack"><!--Wrap Exceptions you are re-throwing-->
<h2>Wrap Exceptions You re-throw/raise</h2>
<section>
<p class="fragment">Define Exceptions for the Callers Needs.</p>
<aside class="notes">
<p>This applies to working with 3rd party libraries.</p>
<p>You should only catch exceptions you throw where they can be handled.</p>
</aside>
</section>
<section><!--Example of not wrapping exception -->
<pre><code class="hljs lang-python">import sqlite3
class SettingsRepository:
def __init__(self):
self.connection = sqlite3.connect('example.db')
def add(self, setting):
cursor = self.connection.cursor()
cursor.execute(
f'INSERT INTO settings (key, val) VALUES (?, ?)', setting
)
</code></pre>
<aside class="notes">
<p>By wrapping Exceptions thrown by thrid party libraries you are reducing the dependency on that library.</p>
</aside>
</section>
<section><!--Example wrapping exception-->
<pre><code class="hljs lang-python">import sqlite3
class SettingRepository:
def __init__(self):
self.connection = sqlite3('example.db')
def add(self, setting):
try:
cursor = self.connection.cursor()
cursor.execute(
f'INSERT INTO settings (key, val) VALUES (?,?)', setting
)
except IntegrityError as ie:
raise DuplicateSettingError(
f'{setting[0]} already exists', ie
)
</code></pre>
</section>
<section><!--Setting up exception wrapping in Python-->
<pre><code class="hljs lang-python">class AppError(Exception):
def __init__(self, message, inner):
super(AppError, self).__init__(self, message)
self.inner = inner
class DuplicateSettingError(AppError):
pass
</code></pre>
</section>
</section>
<section class="stack"><!--Only Log when you can handle the exception-->
<h2>Only Log Where Exception is Consumed</h2>
<section>
<p class="fragment">This only works if you are providing context.</p>
<aside class="notes">
<ul>
<li>Heckendorn's Law</li>
<li>Using Context Specific Exceptions i.e. Wrap Exceptions</li>
</ul>
</aside>
</section>
<section><!--Horrible logging-->
<pre><code class="hljs lang-python">def jump(speed):
raise BorgException(f'failed jump to warp {speed}')
def jump_to_warp(speed):
try:
jump(speed)
except BorgException as be:
logger.exception(be); raise be
if __name__ == '__main__':
try:
jump_to_warp(5)
except BorgException as be:
logger.exception(be)
</code></pre>
</section>
<section><!--Better Logging with Riker Maneuver-->
<pre><code class="hljs lang-python">def jump(speed):
raise BorgException(
f'failed jump to warp {speed}. Resistance is futile.'
)
def jump_to_warp(speed):
jump(speed)
if __name__ == '__main__':
try:
jump_to_warp(5)
except BorgException as be:
logger.exception(be)
riker_maneuver() # https://youtu.be/P40LIQtEE3M
</code></pre>
</section>
</section>
<section><!--Differentiation-->
<h2>Differentiation</h2>
<aside class="notes">
<p>Set yourself apart by making it easier for developers to consume your libraries.</p>
</aside>
</section>
<section><!--Don't use checked exceptions-->
<h2>Don't Use Checked Exceptions</h2>
<p class="fragment">Looking at you Java!</p>
</section>
<section><!--Document the exceptions you throw-->
<h2>Document the exceptions you raise/throw</h2>
<aside class="notes">
<p>It's all the benefits of checked exceptions without the drawbacks.</p>
<p>Often times it's more interesting to know what happens when something fails rather than when it works.</p>
<ul>
<li>Network Errors</li>
<li>Disk Errors</li>
<li>OS Errors</li>
</ul>
</aside>
</section>
<section><!--Being Exceptional-->
<h2>Exceptionally dealing with libraries exceptions</h2>
<aside class="notes">
<p>Not talking about any one here because you are all perfect developers and will follow everything we've talked about so far
however when you have to deal with third party libraries that didn't attend this talk.
</p>
</aside>
</section>
<section class="stack"><!--Wrap Exceptions-->
<h2>Wrap Exceptions</h2>
<section>
<p class="fragment">and throw a common exception type</p>
</section>
<section><!--Example catching all the exceptions-->
<pre><code class="hljs lang-cs">ACMEPort port = new ACMEPort();
try {
port.open();
} catch (DeviceResponseException e) {
reportPortError(e);
logger.log("Device Response exception", e)
} catch (ATM121UnlockedException e) {
reportPortError(e);
logger.log("Device Response exception", e)
} catch (GMXError e) {
reportPortError(e)
logger.log("Device Response exception", e)
} finally {
..
}
</code></pre>
</section>
<section><!--Example raising common exception-->
<pre><code class="hljs lang-cs">public class LocalPort {
private ACMEPort port;
public void open() {
try {
this.port.open();
} catch (DeviceResponseException e) {
throw new PortException(e);
} catch (ATM121UnlockedException(e)) {
throw new PortException(e);
} catch (GMXError e) {
throw new PortException(e);
}
}
}
</code></pre>
</section>
<section><!--Example of calling code with common exceptions-->
<pre><code class="hljs lang-cs">LocalPort port = new LocalPort();
try {
port.open();
} catch (PortException e) {
reportError(e)
logger.log(e.getMessage(), e)
}
</code></pre>
</section>
</section>
<section class="stack"><!--Use Special Case Pattern-->
<h2>Use Special Case Pattern</h2>
<section>
<p>or the null object pattern</p>
</section>
<section><!--Client code without using Special Case Object-->
<pre><code class="hljs lang-cs">public calculatePay(int employeeId) {
Employee employee = this.employees.FindByID(employeeId);
if (employee != null) {
if employee.isHourly() {
return employee.rate() * employee.hoursWorked();
}
return employee.rate();
}
return 0;
}
</code></pre>
</section>
<section><!--Example of client code using Special Case Pattern.-->
<p>It's much cleaner without null checks.</p>
<pre><code class="hljs lang-cs">public calculatePay(int employeeId) {
Employee employee = this.employees.FindById(employeeId);
if (employee.isHourly()) {
return employee.rate() * employee.hoursWorked();
}
return employe.rate();
}
</code></pre>
</section>
<section>
<p>return a special case when no employee is found</p>
<pre><code class="hljs lang-cs">public EmployeeRepository {
public Employee FindById(int id) {
try {
this.employees.Where(e => e.Id == id);
} catch (EmployeeNotFoundException e) {
return NotFoundEmployee()
}
}
}
</code></pre>
</section>
<section><!--Definition of NotFoundEmployee-->
<p>Special Case Object</p>
<pre><code class="hljs lang-cs">public NotFoundEmployee : IEmployee {
public bool isHourly() { return false; }
public double rate() { return 0.0; }
public int hoursWorked() { return 0; }
}
</code></pre>
</section>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info about config & dependencies:
// - https://github.com/hakimel/reveal.js#configuration
// - https://github.com/hakimel/reveal.js#dependencies
Reveal.initialize({
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }
]
});
</script>
</body>
</html>