Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8609

Troubleshooting • Re: How do I call a function if there is an error?

$
0
0
The key thing to understand with exception handling is where your code will resume after the exception has been handled. (Hint: it's the first line after the end of the code block)

Try running the following two noddy python scripts:

Script 1:

Code:

from time import sleeptry:    while True:        print('.')        print(1/0)        sleep(2) except ZeroDivisionError:     print('Oops!')
Script 2:

Code:

from time import sleepwhile True:    try:        print('.')        print(1/0)        sleep(2)    except ZeroDivisionError:        print('Oops!')
The first will fail once then exit. The second will continue looping until you kill it or hit ctl+c. Don't worry about ZeroDivisionError, that's there so ctrl-c will still function as you'd expect.

Statistics: Posted by thagrol — Tue Apr 02, 2024 11:18 pm



Viewing all articles
Browse latest Browse all 8609

Trending Articles