PYTHON Tutorial

Error Handling

Key Concepts

  • Python try except: Allows you to catch and handle errors.
  • Python finally: Executes regardless of whether an error is raised or not.
  • Custom exceptions: Define your own exceptions to handle specific errors.

Practical Steps

  • Use the try-except block: Wrap potentially error-prone code inside a try block and handle errors in the except block.
  • Catch specific errors: Use specific except clauses to catch particular types of errors, e.g., except ValueError, except IndexError.
  • Handle general errors: Use the general except clause to catch any unexpected error, e.g., except Exception.
  • Use the finally block: Execute code that should always run, regardless of errors, e.g., closing files, releasing resources.
  • Raise custom exceptions: Define custom exceptions using the raise keyword to handle specific scenarios.

Example

try:
    # potentially error-prone code
    result = int(input("Enter a number: "))
except ValueError:
    print("Invalid input. Please enter an integer.")
finally:
    # cleanup code
    print("Exiting program.")

Improved Guide

Error Handling in Python (Simplified)

Key Concepts
  • Try and Except: Catch and handle errors.
  • Finally: Do stuff after trying.
  • Custom Errors: Make your own errors.
Steps

Try and Catch:

  • Try: Run code that might fail.
  • Except: Catch errors if they happen.

Finally:

  • Do stuff always, even if there's an error.

Custom Errors:

  • Make your own errors using raise.
Example
try:
    age = int(input("How old are you?"))
except ValueError:
    print("Invalid input. Please enter a number.")
finally:
    print("Thank you for participating.")