SyntaxError
>>> fro i in range(10):
File "<stdin>", line 1
fro i in range(10):
^
SyntaxError: invalid syntax
NameError
>>> test
# NameError: name 'test' is not defined
TypeError
len(5)
# TypeError: object of type 'int' has no len()
"test" + []
# TypeError: cannot concatenate 'str' and 'list' objects
IndexError
list = ["hello"]
list[2]
# IndexError: list index out of range
ValueError
int("foo")
# ValueError: invalid literal for int() with base 10: 'foo'
När man pratar om felhantering stöter man i termer som att kasta ett exception (throw exception) och fånga ett exception (catch exception).
När man kastar ett exception så talar man om att det har blivit ett fel och definierar vilket fel som ska uppbringas. Sedan fångar man felet och agerar därefter.
I Python kallas det raise exception. För att själv tvinga fram det använder man:
raise ValueError('Ett argument har inte rätt datatyp')
def colorize(text, color):
colors = ("cyan", "yellow", "blue", "green", "magenta")
if type(text) is not str:
raise TypeError("text must be of type str")
if color not in colors:
raise ValueError("color is invalid color")
print(f"Printed {text} in {color}")
colorize([], 'cyan')
# colorize(34, "red")
try:
# Någon kod
except:
# Körs om ett undantag kastas från
# try-blocket
Try-blocket innehåller koden som eventuellt kastar ett undantag, medan exception-blocket fångar och hanterar undantaget.
ATT HANTERA FELEN SOM UPPKOMMER
try:
result = x / y
except ZeroDivisionError:
print('Divided by zero')
print('Här kör koden vidare')
try:
result = x / y
except ZeroDivisionError:
print("Make sure no divisions by 0 are made.")
except NameError:
print("Make sure both numbers are defined.")
print('Här kör koden vidare')
try:
result = x / y
except ZeroDivisionError:
print("Make sure no divisions by 0 are made.")
except NameError:
print("Make sure both numbers are defined.")
else:
print("There were no errors.")
print('Här kör koden vidare')
try:
result = x / y
except ZeroDivisionError:
print("Make sure no divisions by 0 are made.")
except NameError:
print("Make sure both numbers are defined.")
else:
print("There were no errors.")
finally:
print("Process completed.")
print('Här kör koden vidare')
try:
block att försöka
except:
block för undantagshantering
else:
block om allt gick bra
finally:
block som alltid utförs
Python dokumentation för exceptions