0

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.

1
  • Python doesn't have a concept of type-coercion, this why concatenating a Exception to a str doesn't make a Exception turn into a string. Commented Aug 3, 2020 at 6:34

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.