May-23-2022, 09:30 PM
(This post was last modified: May-23-2022, 09:30 PM by Gribouillis.)
Clunk_Head Wrote:Can you please provide an example where an exception must be used in place of anything else?Exceptions free intermediary code from checking all the obstacles that can occur for completing a task. For example
def get_cup_of_coffee(): go_to_recreation_room() open_the_door() go_to_coffee_machine() insert_coin() push_button() cup = take_coffee() return cupMany things can go wrong. The door could be locked, the machine could be in maintenance, the coin could be rejected, etc. All these events, which are not errors should raise an exception when the corresponding function is called. But the logic of
get_cup_of_coffee()
does not need to handle these exceptions. It lets them propagate and they all result in get_cup_of_coffee()
sending an exception.Now the code that uses this function can freely decide to catch the exceptions or not, for example
def ten_o_clock_routine(): try: coffee = get_cup_of_coffee() except RecreationRoomLocked: # take appropriate action except Exception: # other errors else: coffee.drink()The main gain is to choose at which level we catch the exceptions in the code (if they are caught).
In a language without exceptions, such as C,
get_cup_of_coffee()
would have the responsibility to handle all the exceptional cases that can happen in the functions that it calls. In some other languages, we would need to declare all the exception types that are thrown by the function, which is tedious. But not in Python.