Python try except - Include the custom message in the Error variable - python

Im trying to do a simple try except, and it is working. But I want to add some custom string at the beginning of the error message. If I just add it in print, its giving error.
import sys
try:
with open('./datatype-mapping/file.json') as rs_mapping:
data_mapping = json.load(rs_mapping)
except Exception as error:
print('CUSTOM ERROR: '+error)
sys.exit(1)
The error I got is,
Traceback (most recent call last):
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 22, in get_datatype_mapping
with open('./datatype-mapping/file.json') as rs_mapping:
FileNotFoundError: [Errno 2] No such file or directory: './datatype-mapping/file.json'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 102, in <module>
main()
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 99, in main
target_mapping()
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 39, in target_mapping
data_mapping = get_datatype_mapping()
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 26, in get_datatype_mapping
print('ERROR: '+error)
TypeError: can only concatenate str (not "FileNotFoundError") to str
But if I use just print(error) - this is working.

You need to convert error to str.
import sys
try:
int("fail")
except Exception as error:
print('CUSTOM ERROR: ' + str(error))
sys.exit(1)
This works flawlessly.

Related

Unable to catch exception: another exception occurred

I have the following code:
import pandas as pd
index = 2
timestamps = pd.date_range('2019-05-01', '2019-05-01')
try:
timestamp = timestamps[index]
except IndexError:
raise IndexError('index is out of timestamps.')
that results in the following being printed to the terminal
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/datetimes.py", line 1170, in __getitem__
result = self._data.__getitem__(key)
File "/usr/local/lib/python3.7/site-packages/pandas/core/arrays/datetimelike.py", line 426, in __getitem__
val = getitem(key)
IndexError: index 2 is out of bounds for axis 0 with size 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
IndexError: index is out of timestamps.
Why is IndexError: index is out of timestamps. simply not raised in this instance, please?
It was raised. The traceback provides info about the former error which was handled during the latter. Since you catch the exception and raise another, the traceback info includes both.
It is written in the description:
During handling of the above exception, another exception occurred:
You can try and raise another type of error and see that this is the error that was raised.
Because the raise statement in except block forces a new exception to handle the exception occurred in try block.
See python documentation

Syntax Error in Python in Try, Except Block

I am running someone else's code:
./run_me.sh
Traceback (most recent call last):
File "train.py", line 13, in <module>
import options
File "/Users/test/Desktop/lang-emerge/options.py", line 44
except IOError, msg: parser.error(str(msg));
^
SyntaxError: invalid syntax
I tried modifying the except block, but again I get an error:
./run_me.sh
Traceback (most recent call last):
File "train.py", line 13, in <module>
import options
File "/Users/test/Desktop/lang-emerge/options.py", line 44
except: IOError, msg: parser.error(str(msg));
^
SyntaxError: only single target (not tuple) can be annotated
The code where error is:
try: parsed = vars(parser.parse_args());
except: IOError, msg: parser.error(str(msg));
Don't know what to do to resolve the error? The msg is a keyword in python try/except blocks.
With the modified code, IOError as msg:
I get:
./run_me.sh
Traceback (most recent call last):
File "train.py", line 13, in <module>
import options
File "/Users/test/Desktop/lang-emerge/options.py", line 44
except: IOError as msg: parser.error(str(msg));
^
SyntaxError: invalid syntax
except: IOError as msg: parser.error(str(msg));
You have unnecessary colon. You should remove it: Below code is the correct one.
except IOError as msg: parser.error(str(msg));

Printing precise error messages in Python

Is there a way to get more specific Error messages in Python? E.g The full error code or at least the line the error occurred on, the exact file that cannot be found rather than a generic "The system cannot find the file specified")
for file in ['C:/AA/HA.csv', 'C:/AA1/HA1.csv']:
try:
os.remove(file)
except OSError as e:
pass
print(getattr(e, 'message', repr(e)))
#print(getattr(e, 'message', repr(e)))
#print(e.message)
#print('File Not Removed')
The following prints twice:
FileNotFoundError(2, 'The system cannot find the file specified')
While this is great, is there a way to get more precise error messages for bug fixing?
The following stops the job but gives out in console the exact line being 855 as well as the file directory ''C:/AC/HA.csv''.
os.remove('C:/AA/HA.csv')
Traceback (most recent call last):
File "C:/ACA.py", line 855, in <module>
os.remove('C:/AC/HA.csv')
FileNotFoundError: [WinError 2] The system cannot find the file specified: ''C:/AC/HA.csv''
See the traceback module:
import os
import traceback
for file in ['C:/AA/HA.csv', 'C:/AA1/HA1.csv']:
try:
os.remove(file)
except OSError as e:
traceback.print_exc()
Output:
Traceback (most recent call last):
File "C:\test.py", line 6, in <module>
os.remove(file)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/AA/HA.csv'
Traceback (most recent call last):
File "C:\test.py", line 6, in <module>
os.remove(file)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/AA1/HA1.csv'

Python `Error in atexit._run_exitfuncs`

I am trying to use kafka MultiProcessConsumer but I am getting following error. It seems like error is related to multithreading in python
Here is the code which I am using.
simple.py
from kafka import SimpleProducer, SimpleClient, SimpleConsumer, MultiProcessConsumer
# To consume messages
client = SimpleClient('localhost:9092')
consumer = MultiProcessConsumer(client, "my-group", "testing_topic", num_procs=3)
for message in consumer:
# message is raw byte string -- decode if necessary!
# e.g., for unicode: `message.decode('utf-8')`
print(message)
client.close()
Error while running above code.
$ python simple.py
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/var/users/ec2-user/.pyenv/versions/3.6.0/lib/python3.6/multiprocessing/managers.py", line 749, in _callmethod
conn = self._tls.connection
AttributeError: 'ForkAwareLocal' object has no attribute 'connection'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/var/users/ec2-user/.pyenv/versions/3.6.0/lib/python3.6/multiprocessing/connection.py", line 614, in SocketClient
s.connect(address)
FileNotFoundError: [Errno 2] No such file or directory

KeyError when assigning ''praw.Reddit'' to variable

I could successfully connect to reddit's servers with oauth2 some time ago, but when running my script just now, I get a KeyError followed by a NoSectionError. Code is below followed by exceptions, (The code has been reduced to its essentials).
import praw
# Configuration
APP_UA = 'useragent'
...
...
...
r = praw.Reddit(APP_UA)
Error message:
Traceback (most recent call last):
File "D:\Directory\Python\lib\configparser.py", line 843, in items
d.update(self._sections[section])
KeyError: 'useragent'
A NoSectionError occurred when handling the above exception.
"During handling of the above exception, another exception occurred:"
'Traceback (most recent call last):
File "D:\Directory\Python\Projects\myprj for Reddit, globaloffensive\oddshotcrawler.py", line 19, in <module>
r = praw.Reddit(APP_UA)
File "D:\Directory\Python\lib\site-packages\praw\reddit.py", line 84, in __init__
**config_settings)
File "D:\Directory\Python\lib\site-packages\praw\config.py", line 47, in __init__
raw = dict(Config.CONFIG.items(site_name), **settings)
File "D:\Directory\Python\lib\configparser.py", line 846, in items
raise NoSectionError(section)
configparser.NoSectionError: No section: 'useragent'
[Finished in 0.2s]
Try giving it a user_agent kwarg.
r = praw.Reddit(useragent=APP_UA)

Categories

Resources