How do I capture all error & display an error message - python-3.x

In my python code, I would like to catch all the errors & display an error message. For example, I would like to do this thing
try:
'my code block
catch:
print("Error:x error occurred" )
Can you suggest me how to do this?

If you're interested in the exception type, then you can catch all exceptions using except Exception as ex (ex can be anything), and then get the exception type using type(ex).__name__:
try:
# example, dividing by zero
x = 1 / 0
except Exception as ex:
print("Error: {} error occurred".format(type(ex).__name__))
Output:
Error: ZeroDivisionError error occurred
If the type doesn't matter, then this will do:
try:
# some code
except:
print("Error:an error occurred") # any error, but you don't know which

Related

Get rid of "Lost access to message queue" in a simple Python script

The little script below gives me "Lost access to message queue" when it ends.
I'm not very good at Python. So how do I get rid of it?
pi#raspberrypi:$ peder.py
25.0 41.0
Temp: 77.0 F / 25.0 C Humidity: 41%
Lost access to message queue
Script:
#!/usr/bin/python3
import sys
import board
import time
import adafruit_dht
dhtDevice = adafruit_dht.DHT11(board.D17)
try:
# Print the values to the serial port
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print("%-3.1f " % temperature_c + " " + "%-3.1f " % humidity)
print(
"Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(
temperature_f, temperature_c, humidity
)
)
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
time.sleep(2.0)
except Exception as error:
dhtDevice.exit()
raise error
Your code has these lines at the end.
except Exception as error:
dhtDevice.exit()
raise error
This code will run if your script crashes within the try block. It turns off the dhtDevice. Assuming that your program does not crash, this code will not run, and your dhtDevice is never turned off. That seems to be what causes the "Lost access to message queue" message.
To solve it you should only have to add dhtDevice.exit() at the very end of your script. Make sure it's not indented, so it's not part of the except block.

Exception Type: <class 'OSError'>. Arguments: [[WinError 1155] No application is associated with the specified file for this operation:

I am trying to print pdf using FPDF. The pdf is generating successfully for every order but whenever I am trying to print the pdf by using os.startfile it gives me the os error. I am using fpdf 1.7.2 version. I have attached the code and also the error. Can anyone suggest me how to solve this things?
try:
gv.error_log("inside try block")
gv.error_log("===============self.print_file=============")
os.startfile(self.print_file, "print")
gv.error_log("end try block")
except Exception as e:
exception_message = str(e)
exception_type, exception_object, exception_traceback = sys.exc_info()
filename = os.path.split(exception_traceback.tb_frame.f_code.co_filename)[1]
gv.error_log(str('Raised error due to ' + (
f"An Exception Occured. \n Exception Type: {str(exception_type)}. Arguments: [{exception_message}]. File Name: {filename}, Line no: {exception_traceback.tb_lineno}")))
> --> Error: Raised error due to An Exception Occured.
Exception Type: <class 'OSError'>. Arguments: [[WinError 1155] No application is associated with the specified file for this operation.

REST API exception handling with a loop and if statements

I wish to use exception handling for a REST API within a loop. The if/else loop works without the exception handling but once I add try/except my loop breaks and only processes the first couple blocks.
The code below is my attempt at this. The if statement is needed for NONE response by the API while the exception handling is for API error responses.
result of successful API and Error API Call
Printed OUTPUT
---------------------------------------------------------------
['#portland,oregon', 'Hamedan,Iran', '#United Arab Emirates', 'Irani, Brasil', 'NewYork', 'Kuwait']
THIS IS THE CURRENT URL: https://geocode.search.hereapi.com/v1/geocode?q=#portland,oregon&apikey=######
Dictionary Results: {'error': 'Unauthorized', 'error_description': 'No credentials found'}
------------------------------------------------------
Error
------------------------------------------------------
KeyError Traceback (most recent call last)
/var/folders/r5/kk4m049n3ts16vn25dwjnjxc0000gn/T/ipykernel_41052/796175789.py in <module>
27 print('Dictionary Results:',results)
28
---> 29 if results['items'] == []:
30 output = ('NULL','NULL','NULL','NULL',addresses[q])
31 #print('NULL OUTPUT:', output), '\n'
KeyError: 'items'
iter_len=len(addresses)
for q in range(iter_len):
geocode_url = "https://geocode.search.hereapi.com/v1/geocode?q{}".format(addresses[q])+ "&apikey=###"
try:
results = requests.get(geocode_url)
print('THIS IS THE CURRENT URL:', geocode_url), '\n'
except requests.exceptions.RequestException as err:
repr(err)
else:
results = results.json()
print('DICTIONARY RESULTS:',results)
if results['items'] == []:
output = ('NULL','NULL','NULL','NULL',addresses[q])
append_list_as_row(output_filename, output)
continue
else:
output = (
results['items'][0]['position']['lat'],
results['items'][0]['position']['lng'],
results['items'][0]['address']['countryCode'],
results['items'][0]['address']['countryName'],
addresses[q]
)
print('GEOCODED LIST:', output), '\n'
append_list_as_row(output_filename, output)
This question was answered by #Nullman. An IF statement to check RESULTS for the variable 'items' followed by 'continue' in the first ELSE block. The snippet is shown below.
try:
results = requests.get(geocode_url)
except requests.exceptions.RequestException, err:
# print('THIS IS THE CURRENT URL:', geocode_url), '\n'
repr(err)
else:
results = results.json()
print ('Dictionary Results:', results)
if 'items' not in results:
continue

How can I catch any error and get the error itself in Nim

I want to catch any error and get the error itself
It's possible to get the error of specific type
try:
raise newException(CatchableError, "some error")
except IOError as e:
echo e.msg
And it's possible to get any error, but the special function need to be called to get the error which feels really wrong
try:
raise newException(CatchableError, "some error")
except:
let e = getCurrentException()
echo e.msg
Is there a way to do it like:
try:
raise newException(CatchableError, "some error")
except e:
echo e.msg
Any catchable error should extend CatchableError, so this should do what you want:
try:
raise newException(IOError, "some error")
except CatchableError as e:
echo e.msg

How to catch errors (Smartsheet API Python SDK)

I am missing fundamental knowledge.
How to 'properly' catch errors returned by the API.
I'm using Python 3.+
If I pass in the wrong sheet ID
try:
update_sht = SmSh.Sheets.get_sheet(dd_id)
print("OK?:", update_sht, flush=True)
except:
print("Error Print:\n", update_sht)
I get this response (in the IPython console)
Response: {
status: 404 Not Found
content: {
{
"errorCode": 1006,
"message": "Not Found",
"refId": "jod4cgoou0sw"
}
}
OK?: {"result": {"code": 1006, "errorCode": 1006, "message": "Not Found",
"name": "ApiError", "recommendation": "Do not retry without fixing the
problem. ", "refId": "jod4cgoou0sw", "shouldRetry": false,
"statusCode": 404}}
and while it returns an error response, it isn't an exception according to try/except.
At this point, I would like to exit out of the loop I am in, instead of continuing on until I get to other lines of code like this
for col in update_sht.columns:
that DO give errors that cause the program to fail.
Traceback (most recent call last):
File "<ipython-input-195-85dde6ec7071>", line 1, in <module>
xxx(debug=False)
File "<ipython-input-194-0b889c817b08>", line 75, in xxx
for col in update_sht.columns:
AttributeError: 'Error' object has no attribute 'columns'
I'm doing more than one thing on the sheet, if I find it, and would prefer not to have a try/except around error line of code (I exaggerate) unless I need them for other errors.
I know/hope this is easier than I have been trying to make it, but as I opened with, I am missing something fundamental.
-Craig
---- UPDATE ----
I am going around in circles.
If errors_as_exceptions is true, then this
update_sht = SmSh.Sheets.get_sheet(dd_id)
raises and exception, but
print(update_sht)
or anything similar shows the previous good value in the object.
How do I determine the status code and error codes so I can take appropriate action?
Nothing I have tried has worked.
If errors_as_exceptions is false, then this
update_sht = SmSh.Sheets.get_sheet(dd_id)
print(update_sht.result.code)
gives me the error code, but only when there is an error ... so I need to catch the error that occurs when there is no
error.
If I raise the error (errors_as_exceptions=True), how do I determine the status code and error code and if I don't raise the error,
how do I do the same?
I want to prevent my code from failing and give the user useful information on what needs to be fixed.
If you set ss.errors_as_exceptions() and your code looks something like this
try:
my_sheet = ss.Sheets.get_sheet(sheet_ID)
print(my_sheet)
except Exception as e:
print(e.message)
The result will look something like this 1006: Not Found. So, the exception message appears to be errorCode:message.
If you want the Python SDK to raise exceptions for API errors call the errors_as_exceptions method on the client object, e.g.
ss = smartsheet.Smartsheet()
ss.errors_as_exceptions()

Resources