August 2018
Intermediate to advanced
332 pages
9h 12m
English
This method will throw the exception at the line where the generator is currently suspended. If the generator handles the exception that was sent, the code in that particular except clause will be called, otherwise, the exception will propagate to the caller.
Here, we are modifying the previous example slightly to show the difference when we use this method for an exception that is handled by the coroutine, and when it's not:
class CustomException(Exception): passdef stream_data(db_handler): while True: try: yield db_handler.read_n_records(10) except CustomException as e: logger.info("controlled error %r, continuing", e) except Exception as e: logger.info("unhandled error %r, stopping", e) db_handler.close() ...