Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising a custom message for exception in function

MWE of my code distribution:

main.py
../func1.py

From main.py I call func1.py with:

data_list = [elem1, .., elemN] # Data input.
params = [1., 2., 5.] # Some parameters.

for elem in data_list:
    try:
        func1(elem, params) # Call function.
    except Exception:
        print traceback.format_exc()

This way if the function fails for some element, the main code keeps running executing the remaining elements in the list.

I want to insert a custom error message for a given block of func1, so I've defined:

try:
    # try something
except ValueError:
    raise ValueError('Custom error message.')

When a ValueError occurs in func1 the output I get with this, before jumping to the next element in data_list, is:

Traceback (most recent call last):
  File "/main.py", line 44, in main
    func1(params)
  File "/func1.py", line 68, func1
    raise ValueError('Custom error message.')
ValueError: Custom error message.

Why is the custom error message being printed twice?

like image 831
Gabriel Avatar asked Mar 03 '26 19:03

Gabriel


1 Answers

The exception is not raised twice. There can be only one exception "up in the air".

What you are seeing is the whole traceback, an extraordinary help when it comes to finding out why and where your programme crashed, It prints line by line all the frames and ends in the line where the exception was thrown. Therefore you can read your message "again".

If you catch it and print it, you will only see the exception itself. For instance

>>> try:
...   raise ValueError('Custom error message.')
... except ValueError as exc:
...   print exc
... 
Custom error message.
>>> 
like image 53
bgusach Avatar answered Mar 05 '26 08:03

bgusach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!