#5 – Error Handling Flashcards

(9 cards)

1
Q

How do you write a basic try-except block?

A

Use try and except to catch errors.

try:     risky_code() except:     print('Something went wrong')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does the finally block do?

A

It runs no matter what, after try and except.
```
try:
risky_code() except:
print(‘Error’)
finally:
print(‘Always runs’)
~~~

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

How do you handle a specific exception type?

A

Add the exception name after except.
~~~
try:
int(‘abc’) except
ValueError:
print(‘Invalid integer’)
~~~

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

How do you catch multiple types of exceptions?

A

Use a tuple of exceptions.
~~~
try:
risky_code()
except (ValueError, TypeError):
print(‘Invalid input’)
~~~

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

How do you get the actual error message?

A

Use as e to access the exception object.
~~~
try:
1 / 0
except ZeroDivisionError as e:
print(e)
~~~

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

When should you avoid a bare except: clause?

A

When you want to avoid catching unexpected exceptions like KeyboardInterrupt or SystemExit.

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

How do you re-raise an exception?

A

Use raise inside except.
```try:
risky_code()
except:
print(‘Logging error…’)
raise
~~~

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

How do you raise a custom exception?

A

Use the raise keyword with an exception.
~~~
raise ValueError(‘Invalid age’)
~~~

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

How do you define your own exception class?

A

Inherit from Exception.
~~~
class MyError(Exception):
pass raise MyError(‘Something went wrong’)
~~~

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