What went wrong and how can we fix it?
Do nothing. Just display an error message.
Handle the error and continue the process.
# Gets weight from the user
weight = int(input("What's your weight? "))
print(f"Your weight is {weight}")
What's your weight? 100
Your weight is 100
# Gets weight from the user
weight = int(input("What's your weight? "))
print(f"Your weight is {weight}")
try block allows you to test a block of code for errors.
except block allows you to handle errors.
else block lets you execute code when there is no error.
finally block allows you to execute code, regardless of the outcome of the try and except blocks.
try: # test errors
print(3/0)
except ZeroDivisionError: # has error
print('You cannot divide by zero')
else: # has no error
print('The division is successfully performed')
finally: # alwas executed
print('This message is always printed')
You cannot divide by zero
This message is always printed
try: # test errors
print(3/1)
except ZeroDivisionError: # has error
print('You cannot divide by zero')
else: # has no error
print('The division is successfully performed')
finally: # alwas executed
print('This message is always printed')
3.0
The division is successfully performed
This message is always printed
no = input('輸入數字:')
print(no + 1)
try: # 測試是否正確
no = input('輸入數字:')
print(no + 1)
except TypeError: # 如果 try 發生錯誤,就執行 except
print('發生錯誤 TypeError')
print('Try 之後的程式')
輸入數字:2
發生錯誤 TypeError
Try 之後的程式
try: # test errors
weight = int(input("What's your weight? "))
print(f"Your weight is {weight}")
except ValueError: # handle the error
print("!!! input weight is error. !!!")
What's your weight? 100
Your weight is 100
What's your weight? aaa
!!! input weight is error. !!!
try: # test errors
weight = int(input("What's your weight? "))
print(f"Your weight is {weight}")
except: # handle the error
print("!!! input weight is error. !!!")
What's your weight? 100
Your weight is 100
What's your weight? aaa
!!! input weight is error. !!!
try: # test errors
x = int(input("What's x? "))
except ValueError: # has error
print("x is not an integer")
print(f"x is {x}")
try: # test errors
weight = int(input("What's your weight? "))
except ValueError: # handle the error
print("!!! input weight is error. !!!")
else:
print(f"Your weight is {weight}")
What's your weight? 100
Your weight is 100
What's your weight? aa
!!! input weight is error. !!!
try: # test errors
x = int(input("What's x? "))
except ValueError: # has error
print("x is not an integer")
else: # no error
print(f"x is {x}")
What's x? 2
x is 2
What's x? a
x is not an integer
while True:
try: # test errors
weight = int(input("What's your weight? "))
except ValueError: # handle the error
print("!!! input is error. try again !!!")
else:
break # weight is ok and break while loop
print(f"your weight is {weight}")
What's your weight? a
!!! input is error. try again !!!
What's your weight? b
!!! input is error. try again !!!
What's your weight? 100
your weight is 100
def main():
weight = get_weight()
print(f"your weight is {weight}")
def get_weight():
while True:
try: # test errors
weight = int(input("What's your weight? "))
except ValueError: # handle the error
print("!!! input is error. try again !!!")
else:
return weight
main()
What's your weight? a
!!! input is error. try again !!!
What's your weight? b
!!! input is error. try again !!!
What's your weight? 100
your weight is 100
def main():
weight = get_weight()
print(f"your weight is {weight}")
def get_weight():
while True:
try: # test errors
return int(input("What's your weight? "))
except: # handle the error
print("!!! input is error. try again !!!")
main()
What's your weight? a
!!! input is error. try again !!!
What's your weight? 100
your weight is 100
def main():
weight = get_weight()
print(f"your weight is {weight}")
def get_weight():
while True:
try: # test errors
return int(input("What's your weight? "))
except: # handle the error
pass
main()
What's your weight? a
What's your weight? b
What's your weight? 100
your weight is 100
def main():
weight = get_number("What's your weight? ")
print(f"your weight is {weight}")
heigh = get_number("What's your heigh? ")
print(f"your heigh is {heigh}")
def get_number(prompt):
while True:
try: # test errors
return int(input(prompt)) # return the int
except: # handle the error
pass
main()
What's your weight? a
What's your weight? 100
your weight is 100
What's your heigh? b
What's your heigh? 100
your heigh is 100
raise
Statementraise
is used to trigger an exception intentionally.Example 1: Division by Zero
def calculate_division(x, y):
if y == 0:
raise ValueError("Cannot divide by zero.")
return x / y
try:
result = calculate_division(10, 0)
except ValueError as e:
print(e)
Example 2: Validating Age
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
elif age < 18:
raise ValueError("Age is below 18.")
else:
print("Age is valid.")
try:
check_age(-5)
except ValueError as e:
print(e)
Example 3: Checking File Extension
def process_file(filename):
if not filename.endswith('.txt'):
raise ValueError("Invalid file type. Only .txt files allowed.")
# File processing logic here
try:
process_file("data.csv")
except ValueError as e:
print(e)
except
block when an exception is raised.raise
allows custom error messages, making debugging easier.raise
for situations where the program should not continue in its current state.