Python脚本停止出现错误而不是继续
我正在使用Telethon进行电报机器人。
我有电话号码列表。如果电话号码有效,请运行脚本,如果它无效,我希望它检查另一个号码。
这是脚本引起我问题的一部分。
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')
如果数字无效,那么我希望脚本打印“无效号码”,然后继续进行。除了丢弃错误'telethon.errors.rpcerrorlist.phonenumberinvaliderror:电话号码无效(由sendcoderequest引起)',然后结束脚本。
丢弃此错误时如何进行脚本?
谢谢
I am using Telethon for a telegram bot.
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.
How can I carry on the script when this error is thrown?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要捕获的例外是
valueError
,但是丢弃的错误是telethon.errors.rpcerrorlist.phonenumberinvaliderror
。因此,您需要捕获该异常:
如果需要,也可以组合错误类型:
当您在
中运行大量代码
时,这特别有用,因此可能发生许多不同的错误。您的最后选择是捕获所有错误使用
,尽管这似乎很有用,它会使调试变得更加困难,因为这会捕获任何错误(这很容易隐藏出意外错误),否则会以错误的方式处理它们“想打印“无效号码”,如果它实际上是
typeerror
或keyboardInterrupt
)。The exception you're catching is
ValueError
, but the error being thrown istelethon.errors.rpcerrorlist.PhoneNumberInvalidError
.So you need to catch that exception instead:
You can also combine error types if needed:
This is especially useful when you're running a lot of code in your
try
and so a lot of different errors could occur.Your last options is to catch every error using
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
orKeyboardInterrupt
for example).