Module 4: Data Collections and Functions
Error Handling: `try` and `except`
Programs can encounter errors (exceptions) during execution. try-except
blocks allow you to handle these errors gracefully instead of crashing the program.
try
block: Contains the code that might raise an exception.except
block: Contains the code to execute if a specific exception occurs in thetry
block. Example:try: num = int(input("Enter a number: ")) result = 10 / num print(result) except ValueError: print("That was not a valid number!") except ZeroDivisionError: print("You cannot divide by zero!")
You can have multipleexcept
blocks for different error types, or a genericexcept Exception:
to catch any error.