If the program runs error, it will be interrupted and print error information in the terminal. These kinds of problems are common in programming. Events that lead to program errors are called exceptions. The method to deal with program exceptions and enable them to execute are called the exception handling.


1.2.9.1 Exceptions

Even though statements or expressions are right in grammar, there are still execution errors. The errors detected in execution are named exceptions.
E.g.

c = 10/0
print(c)

Result:

syntax finish.
>>> 
>>> 
Ready to download this file,please wait!
download ok
exec(open('test.py').read(),globals())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
ZeroDivisionError: division by zero

The example do not have grammar mistakes, but it causes ZeroDivisionError and be interrupted, which leads to stop to execute the program that followed by.

1.2.9.2 Deal with Exception

try……except: to deal with exceptions in MicroPython. Put the statements that may cause exceptions to try to execute; when exceptions occur, jump the least statement in try and jump to except statements to deal with exceptions.

E.g.

>>> try:
...   a = 10/0
...   print(a)
... except:
...   print("error")
... 
error

except could also handle special exceptions, which means except statement is followed by exception name. When no special exception name is followed, it suggests handling all exceptions.
E.g.

def divide(x, y):
  try:
    i = x/y
  except ZeroDivisionError:
    print("division by zero!")
  else:
    print("result is", i) 

divide(5, 0)
divide(5, 2)

Result:

division by zero!
2.5

The example contains an optional else clause in try…except. If try clause do not cause exception, the code must be executed.

try……finally

Statement in finally will be executed no matter exception happens or not, it could be used with try…except..else.
E.g.

def divide(x, y):
  try:
    i = x/y
  except ZeroDivisionError:
    print("division by zero!")
  else:
    print("result is", i)
  finally:
    print("executing finally clause")

divide(5,0)
print() #print a blank line
divide(5, 2)

Result:

division by zero!
executing finally clause

result is 2.5
executing finally clause

results matching ""

    No results matching ""