Search code examples
pythontelethon

Python script stops at error instead of carrying on


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


Solution

  • The exception you're catching is ValueError, but the error being thrown is 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.

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