Understanding Python Exceptions and Error Handling

Aug 8, 2024

CS50's Introduction to Programming with Python - Week on Exceptions

Instructor: David Malan

Overview of Exceptions

  • Definition: Exceptions refer to problems in code that arise when something goes wrong.
  • Syntax Errors: Errors in the code that must be fixed by the programmer; they prevent the program from running.
    • Example: Forgetting to close a string literal results in a syntax error.

Example of Syntax Error

  1. Written code: print("Hello, world" (missing closing quote)
  2. Terminal output: SyntaxError: unterminated string literal
  3. Correction: Close the string literal.

Runtime Errors vs Syntax Errors

  • Runtime Errors: Errors that occur while the program is running, often due to unexpected user input.
  • Defensive Programming: Write code that anticipates errors and handles them gracefully.

Example of Handling User Input

  • Code to prompt user for an integer:
    x = int(input("What's x? "))
    print(f"x is {x}")
    
  • Issue: If user inputs a non-integer (e.g., "cat"), it raises a ValueError.
  • Terminal output example: ValueError: invalid literal for int() with base 10: 'cat'

Handling Value Errors with Try-Except

  • Using try and except keywords to handle errors:
    try:
        x = int(input("What's x? "))
    except ValueError:
        print("x is not an integer")
    
  • Indentation is crucial; only the indented code under try is attempted.
  • except block executes only if an error occurs.

Improving User Experience

  • Use loops to continually prompt the user until valid input is provided:
    while True:
        try:
            x = int(input("What's x? "))
            break
        except ValueError:
            print("x is not an integer")
    
  • Allows for repeated attempts until valid input.

Enhancements to Code Structure

  • Define functions to encapsulate behavior, improving reusability:
    def get_int(prompt):
        while True:
            try:
                return int(input(prompt))
            except ValueError:
                print("Not an integer!")
    
  • Call function in main:
    x = get_int("What's x? ")
    print(f"x is {x}")
    

Code Refinements

  • Passing Parameters: Function can accept different prompts:
    def get_int(prompt):
        # code...
    
  • Raising Exceptions: Programmers can define custom exceptions using raise keyword.

Conclusion

  • Errors are inevitable in programming, but knowing how to handle them is essential:

    • Syntax Errors: Must be fixed to run the program.
    • Value Errors: Handled using try-except to provide user feedback.
  • Understanding and using exceptions will enhance your programming skills.