Section 15: Handling Exceptions Flashcards
Recall
How to raise exceptions
Recall: Raising Exceptions
Communicate something: decide to deliberately stop execution of code by raising exception
```python
raise<some_exception>(message)
~~~</some_exception>
What is the purpose of a try/except
block?
Instead of having a ValueError
message and the program crashing.
Instead, ValueError
will be caught by the except ValueError
’ instruction and whatever is written inside will be executed
-
try/except
blocks allow us to try some code, and if an exception is raised we can catch it and execute different code - Exception that is caught will not cause the program to crash
- Why?
- Do not want to hide bugs
- Want to use to handle exceptions you cannot prevent as a programmer
What are the steps to handle unavoidable errors?
- Identify the code that can potentially produce the error
- Put in try block
- Write code in except block to handle case when error occurs
What is the default except
block?
What to do with multiple exceptions?
For multiple exceptions, want to write single except clause to handle multiple exceptions, you can do so by listing all the exceptions in a tuple
General Error Catching:
- Want catch all possible exceptions with same block
- Should not be done often → want to be as specific as possible when catching an exception
```python
try:
# code might be problematic
except:
# what to do in case of issue
#Whatever comes after
~~~
What is the finally
block?
- After try and except blocks optional
finally
block can be added - Finally block always executes whether or not there is an exception
- It also executes even if there is a
return/continue/break
statement in anytry/except
block, or if an exception occurs inexcept
block
- It also executes even if there is a
- Useful for cleanup