I want something of the form
try:
# code
except *, error_message:
print(error_message)
i.e I want to have a generic except block that catches all types of exceptions and prints an error message. Eg. "ZeroDivisionError: division by zero". Is it possible in python?
If I do the following I can catch all exceptions, but I won't get the error message.
try:
# code
except:
print("Exception occurred")
Try this:
except Exception as e:
print(str(e))
This will allow you to retrieve the message of any exception derived from the Exception base class:
try:
raise Exception('An error has occurred.')
except Exception as ex:
print(str(ex))
Related
I am trying to handle not none or empty list exception while using boto3. I want to know is there any good way of pythonic code to write this.
buckets_list= None
try:
my_region = os.environ['AWS_REGION']
if my_region == 'us-east-1':
try:
s3 = boto3.client('s3')
buckets_list = s3.list_buckets()
except Exception as err:
logging.error('Exception was thrown in connection %s' % err)
print("Error in connecting and listing bucket{}".format(err))
if buckets_list['Buckets']:
# Search for all buckets.
for bucket in buckets_list['Buckets']:
# my code follow to get other things...
else:
print("Buckets are empty in this region")
else:
print("Region not available")
raise Exception("Exception was thrown in Region")
except Exception as err:
logging.error('Exception was thrown %s' % err)
print("Error is {}".format(err))
raise err
Is this the right way or any suggestions would help.
You can use else block of the try except suite. It is useful for code that must be executed if the try clause does not raise an exception.
try:
s3 = boto3.client('s3')
buckets_list = s3.list_buckets()
except Exception as err:
logging.error('Exception was thrown in connection %s' % err)
print("Error is {}".format(err))
else:
# This means the try block is succeeded, hence `buckets_list` variable is set.
for bucket in buckets_list['Buckets']:
# Do something with the bucket
One issue I am seeing from your code is that, if the list_buckets call is failed there is a chance to get NameError at the line if buckets_list['Buckets'] is not None:. Because buckets_list is undefined if the buckets_list call is failed. To understand this try to run the following snippet :)
try:
a = (1/0)
except Exception as e:
print(e)
print(a)
UPDATE
This is how I would implement this,
Use .get method to avoid KeyError
Use else block of the try except suite to specify the code must be executed if the try clause does not raise an exception.
my_region = os.environ.get('AWS_REGION')
if my_region == 'us-east-1':
try:
s3 = boto3.client('s3')
buckets_list = s3.list_buckets()
except Exception as err:
logging.error('Exception was thrown in connection %s' % err)
print("Error in connecting and listing bucket{}".format(err))
else:
buckets_list = buckets_list['Buckets']
if not buckets_list:
print("Buckets are empty in this region")
else:
# Search for all buckets.
for bucket in buckets_list:
pass
# Do something with the bucket
else:
print("Region not available")
Your code is somewhat not detailed enough, at least the beginning of the function should have been shared. Anyway, did you consider:
try:
s3 = boto3.client('s3')
buckets_list = s3.list_buckets()
print("buckets_list", buckets_list['Buckets'])
print("Error is {}".format(err))
if buckets_list['Buckets'] is not None: ##Here I am trying to check if buckets are empty
# Search for all buckets.
for bucket in buckets_list['Buckets']:
(your other codes)
except Exception as err:
logging.error('Exception was thrown in connection %s' % err)
I'm using Python 3.7 and Django and trying to figure out how to rerun a try block if a specific exception is thrown. I have
for article in all_articles:
try:
self.save_article_stats(article)
except urllib2.HTTPError as err:
if err.code == 503:
print("Got 503 error when looking for stats on " + url)
else:
raise
What I would like is if a 503 errors occurs, for the section in the "try" to be re-run, a maximum of three times. Is there a simple way to do this in Python?
You can turn this in a for loop, and break in case the try block was successful:
for article in all_articles:
for __ in range(3):
try:
self.save_article_stats(article)
break
except urllib2.HTTPError as err:
if err.code == 503:
print("Got 503 error when looking for stats on " + url)
else:
raise
In case the error code is not 503, then the error will reraise, and the control flow will exit the for loops.
I am just thinking how to do try and catch with it, what i am trying to achieve is like this:
try:
dbSession.execute(
"INSERT INTO users (username, email, password) VALUES (:username, :email, :password)",
{"username": reg_form.username.data, "email": reg_form.email.data, "password": hashed_password}
)
dbSession.commit()
return jsonify({'success': 'OK'})
except e:
return jsonify({'error': e})
in js, error is passed automatically, but in python i see samples like this,
except ValueError:
is it possible to pass the e automatically in python?
you do except ValueError: if you want to differentiate your catches based on the Error you are getting. Here, you catch a ValueError if you expect an int, but get a str for example.
But you can just keep it generic if you want by doing except:.
As pointed out in Maor Refaeli's comment, you can name your exception as e if you like.
you can read more about python exceptions on this link right here.
You need to catch that Exception First. So here you need to catch the exception ValueError and you can write the error return message to the variable e.
except ValueError as e:
return jsonify({'error': e})
Which is what this code does. Or if you donot want to catch a specific Exception you could just.
except Exception as e:
return jsonify({'error': e})
You can print or return the Value error as below:
except ValueError as err:
print(f"Failed - {err}")
OR
except ValueError as err:
return jsonify({'error': err})
Hey I know I can do try except to resolve ClientError warning but is there any way that exception could be more precise meaning instead of except ClientError: Can I do except InvalidPermission.Duplicate:
This is the complete output I am getting without applying any exceptions:
botocore.exceptions.ClientError: An error occurred (InvalidPermission.Duplicate)
You can get error code like this -
using this-
try:
boto3_api_operation()
except ClientError as e:
code = e.response["Error"]["Code"]
print(code)
#O/p - InvalidPermission.Duplicate
You can read AWS Error Codes Documentation
Let me know,if it helps!
I am using "requests (2.5.1)" .now I want to catch the exception and return an dict with some exception message,the dict I will return is as following:
{
"status_code": 61, # exception code,
"msg": "error msg",
}
but now I can't get the error status_code and error message,I try to use
try:
.....
except requests.exceptions.ConnectionError as e:
response={
u'status_code':4040,
u'errno': e.errno,
u'message': (e.message.reason),
u'strerror': e.strerror,
u'response':e.response,
}
but it's too redundancy,how can I get the error message simplicity?anyone can give some idea?
try:
#the codes that you want to catch errors goes here
except:
print ("an error occured.")
This going to catch all errors, but better you define the errors instead of catching all of them and printing special sentences for errors.Like;
try:
#the codes that you want to catch errors goes here
except SyntaxError:
print ("SyntaxError occured.")
except ValueError:
print ("ValueError occured.")
except:
print ("another error occured.")
Or;
try:
#the codes that you want to catch errors goes here
except Exception as t:
print ("{} occured.".format(t))