← Lesson
Errors and try/except
Joeven
Run
Reset
Python loads on first run
def read_url(url): if not url.startswith("https://"): raise ValueError("only https allowed") if url.endswith("/timeout"): raise ValueError("timed out") return "ok body" def run(url): try: body = read_url(url) except ValueError as e: return {"ok": False, "error": str(e)} else: return {"ok": True, "body": body} finally: print("finished", url) print(run("http://example.com")) print(run("https://example.com/timeout")) print(run("https://example.com")) import json try: json.loads("{not json") except json.JSONDecodeError as e: print("bad json", e.msg)
Run to execute this in your browser. Nothing is sent to a server.