Python try except - 在错误变量中包含自定义消息
Python try except - Include the custom message in the Error variable
我尝试做一个简单的 try except,它正在运行。但我想在错误消息的开头添加一些自定义字符串。如果我只是在打印中添加它,它会出错。
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)
我得到的错误是,
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
但如果我只使用 print(error)
- 这是可行的。
您需要将 error
转换为 str
。
import sys
try:
int("fail")
except Exception as error:
print('CUSTOM ERROR: ' + str(error))
sys.exit(1)
这完美无缺。
我尝试做一个简单的 try except,它正在运行。但我想在错误消息的开头添加一些自定义字符串。如果我只是在打印中添加它,它会出错。
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)
我得到的错误是,
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
但如果我只使用 print(error)
- 这是可行的。
您需要将 error
转换为 str
。
import sys
try:
int("fail")
except Exception as error:
print('CUSTOM ERROR: ' + str(error))
sys.exit(1)
这完美无缺。