Week 5: Functions & Error Handling
def
keyword, a descriptive name, parameters with type hints, a return type, and a numpy-style docstring.try
and except
try...except
block.try
block contains the code that might fail.except
block contains the code that runs only if an error occurs in the try
block.else
and finally
clauseselse
block runs only if the try
block completes successfully (no exception was raised).finally
block runs no matter what. It will always execute, whether an exception happened or not. This is perfect for cleanup code, like closing a file.# A simplified file operation
try:
f = open("my_data.txt")
# ... process the file
except FileNotFoundError:
print("Error: Could not find the file.")
else:
print("File processed successfully.")
finally:
print("Executing cleanup. The 'try' block is now finished.")
# In a real app, you would close the file here: f.close()
try...except
blocks to handle potential runtime errors.labs/lab05/README.md
.IS4010: App Development with AI