Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Catching and Handling Exceptions | Comprehensive Error Handling (Exceptions)
Python Structural Programming

Catching and Handling Exceptions

Stryg for at vise menuen

When you work with file operations or other code that might encounter errors, Python's structured error handling using try, except, else, and finally blocks is essential for writing resilient programs. The try block contains code that might raise an exception. If an exception occurs, the except block runs, allowing you to handle the error gracefully. If no exception is raised, the else block executes, making it a good place for code that should only run when everything in the try block succeeds. The finally block always executes, regardless of whether an exception occurred, making it ideal for cleanup actions like closing files or releasing resources. As you saw in the video, this structure helps you separate normal logic, error handling, and cleanup, resulting in clearer and safer code.

Python Error Handling Blocks

  • The try block contains code that might raise an exception;
  • The except block catches and handles exceptions if they occur;
  • The else block runs only if no exception was raised in the try block;
  • The finally block always runs, whether an exception occurred or not.
123456789101112131415
filename = "example.txt" try: file = open(filename, "w") file.write("Hello, Python error handling!") except OSError as e: print("An error occurred while writing to the file:", e) else: print("File written successfully.") finally: try: file.close() print("File closed.") except Exception: print("File was never opened or already closed.")

This structure allows you to separate normal logic, error handling, and cleanup tasks. Use try for risky code, except for managing errors, else for successful completions, and finally for actions that must always be executed, such as closing files or releasing resources.

question mark

Which statement best describes the execution order of the else and finally blocks in a try, except, else, finally structure?

Vælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 2

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 1. Kapitel 2
some-alt