PLEASE SUBSCRIBE!!!
In the previous lesson ( • Python Programming: Lesson 17 - Ident... ), we learned about exceptions, errors in Python that cause our program to stop executing. Here, we figure out how to deal with exceptions, how to prevent undesirable runtime errors.
An exception is a runtime error that occurs in our code. We can have:
organic exceptions - runtime errors caused by unintentional faults in our code
engineered exceptions - when we choose to manually throw a runtime error
handled exceptions - successful code that prevents a runtime error using a try/except block
We can use a try/except block to handle exceptions. The try block runs as much as it can. If it hits an unsuccessful segment, it goes over to the corresponding except block. If the try block is completely successful, the except block does not run. Regardless of what happens, the finally code will run at the end, before the program has any probability of terminating.
There's also an assert keyword and an AssertionError that we can catch. Suppose that B is some boolean.
try:
assert B
print( "B is True" )
except AssertionError:
print( "B is False" )
0:18 Review of Identifying Exceptions
1:19 Review of Raising Exceptions
3:07 NEW: Catching Exceptions with try/except (ZeroDivisionError)
8:11 NEW: Another Example with try/except (IndexError)
10:25 NEW: Handling Multiple Types of Exceptions Independently
11:43 NEW: Handling Multiple Types of Exceptions the Same
13:00 NEW: assert x Keyword throws a runtime error if and only if x is false
15:39 NEW: try/except/finally Block
18:42 NEW: assert x, y throws a runtime error with message y if and only if x is false
An equivalent lesson in Java is available here: • Java Programming: Lesson 44 - Throwin...
Ready for file I/O? It's cool, I promise! • Python Programming: Lesson 19 - File I/O
Thanks for watching, and PLEASE SUBSCRIBE!!!