0

Let say I have a for loop like this

data = [1, 2, 3, '4', 5]
for d in data:
    print(d * 0)

Output

TypeError: can only concatenate str (not "int") to str

Then if I use Try: except blocks

data = [1, 2, 3, '4', 5]
try:
  for d in data:
    print(d * 0)
except TypeError:
    pass

Output

1
2
3

I wonder, is it possible to get the skipped value
In this case '4'

Or in other words, is it possible to get the value that caused the exception?

My question is not related to just this piece of code but Python overall.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Herker
  • 552
  • 6
  • 20
  • That question is more specific for exception with string right? I'm wondering like python overall if you get me. – Herker May 03 '21 at 11:34
  • That output is not what the program actually outputs... This program won't even cause an Exception, since `'4' * 0` is perfectly legal. So what is your actual problem? – Tim Pietzcker May 03 '21 at 11:43

1 Answers1

3

That is easy, you have the value that failed and you catch that, simply use that value.

for d in data:
   try:
      print(d+1)
   except TypeError:
      print('error caused by', d)
Ceres
  • 2,498
  • 1
  • 10
  • 28
  • Yes, that works, but like in other situations. For example when using Dataframe. And a specific row is causing the exception. Is it possible to handle something like that? – Herker May 03 '21 at 11:33
  • Not sure I understand your question, but you could also print the row in the dataframe. – Ceres May 03 '21 at 11:36
  • Okey, forget about Dataframe. Is it almost always possible to get the value that caused the exception, no matter what situation? – Herker May 03 '21 at 11:40
  • 1
    For a TypeError, yes. You will definitely be able to get the value that caused the error. – Ceres May 03 '21 at 11:46