Зміст курсу
Mastering Python: Annotations, Errors and Environment
Mastering Python: Annotations, Errors and Environment
Handling
Let's consider Python tools that help us to control code execution and errors.
Error Handling Structure
There are different keywords are used to control program errors:
try
: this keyword is used for the code block where we expect the error.except
: this keyword is used for the code block executed if an error is raised.else
: this keyword is used to perform certain logic if errors are not raised.finally
: this keyword is used for the code block that always executes after all structure.
try and except
These are the main keywords for error handling, the try
code block waits for errors, and the except
catches it:
print("Code above is executed") try: 1 / 0 except: print("Error is catched") print("Code below is executed")
The interpreter is not stopped after the ZeroDivisionError
raising because the except
keyword caught it.
Note
Don't try to put all your code inside the
try
block - this will lead to unexpected consequences and can break the program.
If the try
block is executed without errors, the except
block will not be executed.
try: print("No errors") except: print("Error is catched")
The try
block does not roll back executed code. All the code lines before an error are executed:
lst = [] try: lst.append("first") # executed lst.append("second") # executed 1 / 0 # error lst.append("third") # not executed except: print("Error caught") print(lst)
Note
The
try
block raises the exactly one error because executing stops after an error.
else and finally
The else
and finally
blocks are optional and used less often.
try: print("try: Start") # 1 / 0 print("try: End") except: print("except: Error is raised") else: print("else: The try block is executed succesfuly") finally: print("finally: Always executed")
You can add and remove comments in the example above to understand how it works.
Дякуємо за ваш відгук!