Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bypassing and printing out the name of an Error in a Loop – Python

Although I know it is not good practice to bypass an error, I’m trying to figure out in which of the data sets that I am working one, I get an error.

I am looping through all of the Data Sets, and everythime I get an error I flag it by using:

    try:
                # block raising an exception
    except:
       pass     # doing nothing on exception

I managed to flag the ones where the errors appeared by printing their names on the except block, but I would also like to know if anyone knows a way of also printing out the error I am getting (just to make sure it is all the same Error as I expect)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for j in list:
  for i in range(len(j)):
        try:
            run_path = j.iloc[i]
            name = run_path.processed_file
            name1 = name.split('/')
            name_final = name1[2]
            print(name_final)

            time, angle, couple, rpm, Fx, Fy, Fz, Mx, My , Mz , U , V, H = load_data(path_data + run_path.processed_file)
            dt = time[1] - time[0]

            minrose, maxrose, minwave, maxwave = minmaxrose_minmmaxH(Fx, angle, H)

            recap['Cxmin_rose'] = minrose
            recap['Cymmax_rose'] = maxrose
            recap['Cxmin_houle'] = minwave
            recap['Cxmax_houle'] = maxwave

            recap.to_excel(os.path.join(path_data,'recap_essai - JRS.xlsx'))  

            print('')
        except:
            run_path = j.iloc[i]
            name = run_path.processed_file
            name1 = name.split('/')
            name_final = name1[2]
            print('')
            print(name_final + ' ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR')
            print('')
            pass

In this case, list is a list of "blocks of data sets" and i is a data set inside each block.

My Goal here would be to print, alongside the name, the type of error that I get.

Thank you!!

>Solution :

To print the type of error, you can use the following code

try:
# Your code
except Exception as e:
    print(type(e).__name__)

Example:

try:
    1/0
except Exception as e:
    print(type(e).__name__)
# Output:
# ZeroDivisionError

Also see How to print an exception in Python?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading