(Oct-21-2018, 11:12 PM)Pedroski55 Wrote: How can I make the program carry on?
Is that what 'try' is for?
You can catch the error and make it continue with
pass
.
>>> lst = [1, 4, 7, 9, 10, 20, 100]
>>> for n in lst:
... print(f'{2 / n:.2f}')
...
2.00
0.50
0.29
0.22
0.20
0.10
0.02
>>>
>>> lst = [1, 4, 7, 9, 10, 0, 20, 100]
>>> for n in lst:
... print(f'{2 / n:.2f}')
...
2.00
0.50
0.29
0.22
0.20
Traceback (most recent call last):
File "<string>", line 449, in runcode
File "<interactive input>", line 2, in <module>
ZeroDivisionError: division by zero
So when it's a error in list
0
it stop and two last values 20, 100 do not get executed.
>>> lst = [1, 4, 7, 9, 10, 0, 20, 100]
>>> for n in lst:
... try:
... print(f'{2 / n:.2f}')
... except ZeroDivisionError:
... pass
...
2.00
0.50
0.29
0.22
0.20
0.10
0.02
Now it skip error and run last 2 values.
The problem now can be that do not know what happens,to fix this can logg it.
import my_log
lst = [1, 4, 7, 9, 10, 0, 20, 100]
for n in lst:
try:
my_log.logger.debug(n)
print(f'{2 / n:.2f}')
except ZeroDivisionError:
my_log.logger.exception('msg')
pass
logg.log:
Output:
2018-10-22 05:11:04,491 - my_log - DEBUG - 1
2018-10-22 05:11:04,491 - my_log - DEBUG - 4
2018-10-22 05:11:04,491 - my_log - DEBUG - 7
2018-10-22 05:11:04,492 - my_log - DEBUG - 9
2018-10-22 05:11:04,492 - my_log - DEBUG - 10
2018-10-22 05:11:04,492 - my_log - DEBUG - 0
2018-10-22 05:11:04,492 - my_log - ERROR - msg
Traceback (most recent call last):
File "E:\div_code\new\pass_on.py", line 7, in <module>
print(f'{2 / n:.2f}')
ZeroDivisionError: division by zero
2018-10-22 05:11:04,493 - my_log - DEBUG - 20
2018-10-22 05:11:04,493 - my_log - DEBUG - 100
Boilerplate my_log:
# my_log.py
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# create a file handler
handler = logging.FileHandler('logg.log')
handler.setLevel(logging.DEBUG)
# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(handler)