简体   繁体   English

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

[英]Python script stops at error instead of carrying on

I am using Telethon for a telegram bot.我正在将 Telethon 用于电报机器人。

I've got a list of phone numbers.我有一个电话号码列表。 If the phone number is valid then to run a script, if it is invalid I want it to check another number.如果电话号码有效,则运行脚本,如果无效,我希望它检查另一个号码。

This is the part of script which is causing me issues.这是导致我出现问题的脚本部分。

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')

If the number is invalud then I would expect the script to print 'invalid number' and then carry on.如果数字无效,那么我希望脚本打印“无效数字”然后继续。 Except it is throwing error 'telethon.errors.rpcerrorlist.PhoneNumberInvalidError: The phone number is invalid (caused by SendCodeRequest)', then ending the script.除了抛出错误“telethon.errors.rpcerrorlist.PhoneNumberInvalidError: The phone number is invalid (caused by SendCodeRequest)”,然后结束脚本。

How can I carry on the script when this error is thrown?抛出此错误时如何继续执行脚本?

Thanks谢谢

The exception you're catching is ValueError , but the error being thrown is telethon.errors.rpcerrorlist.PhoneNumberInvalidError .您捕获的异常是ValueError ,但抛出的错误是telethon.errors.rpcerrorlist.PhoneNumberInvalidError

So you need to catch that exception instead:因此,您需要改为捕获该异常:

from telethon.errors.rpcerrorlist import PhoneNumberInvalidError

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

You can also combine error types if needed:如果需要,您还可以组合错误类型:

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

This is especially useful when you're running a lot of code in your try and so a lot of different errors could occur.当您在try中运行大量代码并且可能会出现许多不同的错误时,这尤其有用。

Your last options is to catch every error using您最后的选择是使用捕获每个错误

try:
    # code
except Exception:
    print("exception!")

and while this might seem to be useful it will make debugging a lot harder as this will catch ANY error (which can easily hide unexpected errors) or it will handle them in the wrong way (you don't want to print 'invalid number' if it was actually a TypeError or KeyboardInterrupt for example).虽然这可能看起来很有用,但它会使调试变得更加困难,因为这会捕获任何错误(这很容易隐藏意外错误)或者它会以错误的方式处理它们(你不想打印“无效数字”例如,如果它实际上是TypeErrorKeyboardInterrupt )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM