CS50P 3_Exceptions

Exceptions 例外處理機制

exception : unexpected error

Understanding Exceptions in Python

  • Definition:
    An exception is an error that occurs during the execution of a program.
     
  • Common Cause:
    Exceptions are typically caused by factors outside the control of the program (e.g., user input, file not found).

Exception

What went wrong and how can we fix it?

Do nothing. Just display an error message.

Handle the error and continue the process.

To obtain the weight accurately and without any errors.

# 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

input is not a number for weight

# Gets weight from the user 
weight = int(input("What's your weight? ")) 
print(f"Your weight is {weight}")

Exception Handling

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.

Exception Example

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

Exception Example

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

Exception TypeError

no = input('輸入數字:')
print(no + 1)

Exception Handling TypeError

try: # 測試是否正確
    no = input('輸入數字:')
    print(no + 1)
except TypeError: # 如果 try 發生錯誤,就執行 except
    print('發生錯誤 TypeError')
print('Try 之後的程式')
輸入數字:2
發生錯誤 TypeError
Try 之後的程式

Exception Handling ValueError

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. !!!

Exception Handling any 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. !!!

Exception NameError

try: # test errors
    x = int(input("What's x? ")) 
except ValueError: # has error
    print("x is not an integer")
print(f"x is {x}")

Exception else

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. !!!

Exception else

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

I have to get the 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:
        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

using function to get weight

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

using function to get weight

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

using function to get weight

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

using function to get weight and heigh

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

The raise Statement

  • Purpose:
    raise is used to trigger an exception intentionally.
     
  • Use Case:
    Commonly used for input validation or to signal conditions that the program cannot handle.

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)

Key Points to Remember

  • Control Flow:
    Exceptions change the flow of a program. It jumps to the except block when an exception is raised.
  • Error Messaging:
    Using raise allows custom error messages, making debugging easier.
  • Best Practices:
    Only use raise for situations where the program should not continue in its current state.

Discussion and Practice

  • Q&A: What are some scenarios where raising an exception is appropriate?
  • Exercise: Write functions that raise exceptions for various invalid inputs or conditions.
Made with Slides.com