Exception Handling with Copilot Prompts
When writing Python code, errors (called exceptions) can happen at any time. For example, dividing by zero or trying to open a file that doesn’t exist.
Instead of letting your program crash, you can handle exceptions to make your code safer and more user-friendly.
What is an Exception?
An exception is an error that stops the normal flow of a program. Examples include:
- Dividing by zero (
ZeroDivisionError) - Trying to access an item in a list that doesn’t exist (
IndexError) - Converting a string that isn’t a number (
ValueError)
Try-Except Blocks
The try-except block lets you try some code that might fail and catch the error to handle it gracefully.
Prompt
1# Write a function that handles division by zero
Copilot might suggest:
1 2 3 4 5 6def safe_divide(a, b): try: result = a / b return result except ZeroDivisionError: return "Cannot divide by zero"
Explanation
try: Code inside this block is attempted first.except ZeroDivisionError: This block runs only if dividing by zero happens.return: Gives a clear message instead of crashing the program.
Example Usage
1 2print(safe_divide(10, 2)) # Output: 5.0 print(safe_divide(5, 0)) # Output: Cannot divide by zero
Why handle exceptions?
Without a try-except block, dividing by zero would stop your whole program with an error.
Finally Block
Sometimes, you want to run certain code no matter what happens, whether there was an error or not.
The finally block always runs after try-except.
Prompt
1# Show how to use finally block after try-except
Copilot might suggest:
1 2 3 4 5 6 7 8 9def read_file(filename): try: f = open(filename, 'r') data = f.read() return data except FileNotFoundError: return "File not found." finally: print("Execution completed. Closing resources if needed.")
Explanation
try: Tries to open and read a file.except FileNotFoundError: Runs if the file doesn’t exist.finally: Runs regardless of success or failure (e.g., to close files or show a message).
Example Usage
1print(read_file("my_file.txt"))
If the file does not exist, it prints:
1 2Execution completed. Closing resources if needed. File not found.
If it exists, it prints:
1 2Execution completed. Closing resources if needed. <file contents>
Custom Exceptions
Sometimes, you want to define your own errors to make your code more descriptive.
Prompt
1# Create a custom exception called InvalidAgeError
Copilot might suggest:
1 2 3 4 5 6 7 8 9 10class InvalidAgeError(Exception): def __init__(self, message="Age must be between 0 and 120."): self.message = message super().__init__(self.message) def check_age(age): if age < 0 or age > 120: raise InvalidAgeError() else: return "Valid age"
Explanation
class InvalidAgeError(Exception): Defines a new error type that inherits from Python’s built-inException.__init__: Sets a default error message.raise InvalidAgeError(): Raises the error when conditions aren’t met.
Example Usage
1 2 3 4 5try: print(check_age(25)) # Valid age print(check_age(-5)) # This will raise our custom exception except InvalidAgeError as e: print(e) # Output: Age must be between 0 and 120.
Why Use Custom Exceptions?
- Makes your code more clear and specific.
- Helps other developers understand what went wrong.
- Provides better error messages to users.
Key Takeaways
- Use
try-exceptblocks to handle errors without crashing your program. - Use
finallyto run code that should execute no matter what. - Create custom exceptions to make your code clearer and safer.
- Copilot can suggest full exception-handling code if you provide detailed prompts.
Mini Challenge
Prompt:
1# Create a function that opens a file and reads its content. If the file is missing, return "File not found." Always print "Done reading file" at the end.
Practice Exercises
- Write a function to convert a string to an integer. If it fails, return "Invalid number."
- Create a class
NegativeNumberErrorand raise it if a number is negative. - Write a function that divides two numbers and always prints "Operation finished" whether or not an exception occurs.
Extra Tips
- Always read Copilot's suggestions carefully before accepting.
- Add comments explaining what each try-except block does.
- Start with small examples, then build up to more complex error handling.
Frequently Asked Questions
No. This lesson explains everything clearly from the ground up, even if you're new to error handling.
Yes. Copilot can suggest complete error-handling structures, but you should read and understand each suggestion before using it.
It prevents your program from crashing and allows you to show friendly error messages to users.
A custom exception lets you define your own specific error types, making your code easier to understand and debug.
No. You use finally when you need to run some cleanup code regardless of whether an error happened.
Still have questions?Contact our support team