Notes
Syntax errors are grammatical errors such as misspelling a word or using a language element improperly.
Run-time errors are those that appear only after you compile and run your code. Examples are dividing zero, opening a file that does not exist, etc.
Logic errors occur when there is a design flaw in your program. Examples are using wrong formula, adding instead of subtracting, etc.
Errors Handling Syntax
try:
[statements to run when there is no error]
except [exception_name]: #if exception_name is omitted, then it catches all errors.
[statements to run when an error occurs]
finally:
[statements always executed before leaving the try statement, whether an exception has occurred or not]
Errors Handling Example
print(2/0) #no output; ZeroDivisionError occurs
try:
print(2/0)
except ZeroDivisionError:
print("You cannot divide a number by 0!")
#the program catches the ZeroDivisionError and then prints "You cannot divide a number by 0!"
try:
print(2/0)
except NameError:
print("You cannot divide a number by 0!")
finally:
print("This statement always runs.")
#output "This statement always runs.". Even though the error is not caught by the except statement and the ZeroDivisionError occurs, the finally statement clause runs.