Section 15: Handling Exceptions Flashcards

1
Q

Recall

How to raise exceptions

A

Recall: Raising Exceptions
Communicate something: decide to deliberately stop execution of code by raising exception

```python
raise<some_exception>(message)
~~~</some_exception>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the purpose of a try/except block?

A

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?
    1. Do not want to hide bugs
    2. Want to use to handle exceptions you cannot prevent as a programmer
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the steps to handle unavoidable errors?

A
  1. Identify the code that can potentially produce the error
  2. Put in try block
  3. Write code in except block to handle case when error occurs
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the default except block?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What to do with multiple exceptions?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

General Error Catching:

A
  • 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
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the finally block?

A
  • 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 any try/except block, or if an exception occurs in except block
  • Useful for cleanup
How well did you know this?
1
Not at all
2
3
4
5
Perfectly