Python 脚本因错误而停止而不是继续

Python script stops at error instead of carrying on

我正在将 Telethon 用于电报机器人。

我有一个 phone 号码的列表。如果 phone 号码有效,则 运行 一个脚本,如果无效,我希望它检查另一个号码。

这是导致我出现问题的脚本部分。

from telethon.sync import TelegramClient
from telethon.errors.rpcerrorlist import PhoneNumberBannedError

api_id = xxx # Your api_id
api_hash = 'xxx' # Your api_hash

try:
    c = TelegramClient('{number}', api_id, api_hash)
    c.start(number)
    print('Login successful')
    c.disconnect()
    break
except ValueError:
    print('invalid number')

如果数字无效,那么我希望脚本打印 'invalid number' 然后继续。除了抛出错误 'telethon.errors.rpcerrorlist.PhoneNumberInvalidError: The phone number is invalid (caused by SendCodeRequest)',然后结束脚本。

抛出此错误时如何继续执行脚本?

谢谢

您捕获的异常是 ValueError,但抛出的错误是 telethon.errors.rpcerrorlist.PhoneNumberInvalidError

因此您需要捕获该异常:

from telethon.errors.rpcerrorlist import PhoneNumberInvalidError

try:
    # your code
except PhoneNumberInvalidError:
    print('invalid number')

如果需要,您还可以组合错误类型:

except (PhoneNumberInvalidError, ValueError):
    # handle these types the same way
except TypeError:
    # or add another 'except <type>' line to handle this error separately

当您 运行 您的 try 中有很多代码时,这尤其有用,因此可能会出现很多不同的错误。

您最后的选择是使用

捕获每个错误
try:
    # code
except Exception:
    print("exception!")

虽然这看起来很有用,但它会使调试变得更加困难,因为这会捕获任何错误(这很容易隐藏意外错误)或者它会以错误的方式处理它们(你不想例如,如果它实际上是 TypeErrorKeyboardInterrupt,则打印 'invalid number'。