#5 – Error Handling Flashcards
(9 cards)
How do you write a basic try-except block?
Use try
and except
to catch errors.
try: risky_code() except: print('Something went wrong')
What does the finally
block do?
It runs no matter what, after try and except.
```
try:
risky_code() except:
print(‘Error’)
finally:
print(‘Always runs’)
~~~
How do you handle a specific exception type?
Add the exception name after except
.
~~~
try:
int(‘abc’) except
ValueError:
print(‘Invalid integer’)
~~~
How do you catch multiple types of exceptions?
Use a tuple of exceptions.
~~~
try:
risky_code()
except (ValueError, TypeError):
print(‘Invalid input’)
~~~
How do you get the actual error message?
Use as e
to access the exception object.
~~~
try:
1 / 0
except ZeroDivisionError as e:
print(e)
~~~
When should you avoid a bare except:
clause?
When you want to avoid catching unexpected exceptions like KeyboardInterrupt
or SystemExit
.
How do you re-raise an exception?
Use raise
inside except
.
```try:
risky_code()
except:
print(‘Logging error…’)
raise
~~~
How do you raise a custom exception?
Use the raise
keyword with an exception.
~~~
raise ValueError(‘Invalid age’)
~~~
How do you define your own exception class?
Inherit from Exception
.
~~~
class MyError(Exception):
pass raise MyError(‘Something went wrong’)
~~~