
In Python, every exception object has an attribute .args, which is a tuple containing the arguments you passed when raising the exception.
For example:
try: 1 / 0 except Exception as e: print(type(e)) print(e.args) print(e.args[0])
Output:
<class 'ZeroDivisionError'> ('division by zero',) division by zero
Key points:
-
e.argsis always a tuple. -
Its contents depend on how the exception was constructed.
-
If you do
raise ValueError("bad value", 123), thene.args == ("bad value", 123). -
Many built-in exceptions only pass a single string, so
e.args[0]is often the human-readable error message.
-
-
If no arguments were provided when raising the exception,
e.argswill be an empty tuple().
So in your code,
print(e.args[0])
prints the first argument passed to the exception (commonly the error message).
👉 Do you want me to also show you a safe way to print the exception message (without risking IndexError if args is empty)?
You said:
ChatGPT said:
Great 👍 Here’s a safe way to print the exception message without worrying about e.args being empty:
import sys try: # some code 1 / 0 except Exception as e: # Safe way: fall back to str(e) if args is empty msg = e.args[0] if e.args else str(e) print(msg) sys.exit(1)
Why this works:
-
e.args[0]gives you the first argument if it exists. -
If not,
str(e)will still return a meaningful string (e.g.''for an empty exception).
In fact, in most Python codebases people simply use print(str(e)) (or print(e)) because str(e) internally builds a string from e.args.
👉 So the shortest safe version is:
except Exception as e: print(e) # equivalent to print(str(e)) sys.exit(1)

浙公网安备 33010602011771号