I'm using the base64 module for the b64decode() function, however certain strings of text throw this error:
'binascii.Error: Incorrect Padding'.
I understand that this is because the strings are not of length multiple of 4, a requirement of base64 encoded text.
Rather than just adding '='s to the end of the string to make it a multiple of 4, I want to catch the error and simply state that the string is not base64 encoded. It works using a general 'except:', however I want to catch the specific error, but I can't find out the same of the error, as it is not very specific as with other errors, and 'except binascii.Error:' is apparently undefined. Help?
The exception type is stored in binascii.Error
, there's multiple ways of catching the exception:
# 1. you can import the binascii module
import binascii
try:
pass
except binascii.Error as err:
pass
# 2. or you can use the binascii from base64's namespace
try:
pass
except base64.binascii.Error as err:
pass
# 3. or you can use __import__ to do a temp import
try:
pass
except __import__('binascii').Error as err:
pass
The reason
except binascii.Error
didn't work is because binascii was imported from within the base64 namespace, so it was undefined in my working namespace. The correct way to catch the error was
except base64.binascii.Error
Amature mistake
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With