Python Exceptions

ifeelfree
Jan 23, 2021

--

Part 1: What is exception?

  • Builtin exceptions
- BaseException
|----------Exception
|-------ArithmeticError
- GeneratorExit
- KeyboardInterupt
- SystemExit
  • Custom exceptions
raise NotImplementedError

Part 2: How to handle exceptions properly?

  • treat different types of exception differently (else: actions that will be done if no exceptions occur; final: actions will be taken no matter what kind of exceptions we receive)
def get_restaurant_recommendation(path):
try:
config = get_config(path)
user = config["user"]
except FileNotFoundException:
logging.error("VERY UNINFORMATIVE INFORMATION")
raise
except JSONDecodeError:
logging.error("VERY UNINFORMATIVE INFORMATION")
raise
except KeyError:
user = "default_user"
else:
pass
final:
pass
candidates = get_relevant_restaurants(user)
pick_best_restaurants(candidates)
  • suppress exceptions
try:
os.remove('somefile.py')
except FileNotFoundError:
pass
OR
from contexlib import suppress
with suppress(FileNotError):
os.remove('somefile.py')
+-- AttributeError```

--

--

No responses yet