Given the following program:
1 import asyncio
2 async def run():
3 try:
4 server = await asyncio.start_server(on_connected, '127.0.0.1', 15500)
5
6 async with server:
7 await server.serve_forever()
8 except:
9 print("exception!")
10
11 async def on_connected(reader, writer):
12 while True:
13 data = await reader.readline()
14 print(1 / 0)
15
16 asyncio.run(run())
When I run it, and use nc to connect to it & send data, it will raise an exception in line 14. However I am unable to handle it. Instead, I will get an exception printed and the program will hang.
nc test:
$ nc localhost 15500
test
program output:
$ python3 serv
Task exception was never retrieved
future: <Task finished coro=<on_connected() done, defined at serv:14> exception=ZeroDivisionError('division by zero')>
Traceback (most recent call last):
File "serv", line 14, in on_connected
print(1 / 0)
ZeroDivisionError: division by zero
While I of course could just add a try/except around line 14, I want to implement a general exception handling which shall handle all errors which can ever occur inside of on_connected.
How can I do this?