Python Error Handling

Python Error Handling

Error handling in Python is the process of managing errors or exceptions that arise during the execution of a program. Proper error handling ensures your program runs smoothly and fails gracefully when unexpected conditions occur.


Key Concepts in Python Error Handling

  • Exceptions: Exceptions are runtime errors that disrupt the normal flow of a program. Common exceptions include:

    • ZeroDivisionError
    • FileNotFoundError
    • ValueError
    • TypeError
  • try and except:

    • The try block contains code that might raise an exception.
    • The except block catches and handles the exception.
  • else: Executes code if no exceptions occur in the try block.

  • finally: Executes code regardless of whether an exception was raised or not.

  • Raising Exceptions: You can explicitly raise exceptions using the raise statement.

  • Custom Exceptions: You can define your own exceptions by creating a class derived from the Exception class.


  • Syntax and Examples

    1. Basic try and except

      try:
          num = int(input("Enter a number: "))
          result = 10 / num
          print(f"Result: {result}")
      except ZeroDivisionError:
          print("Error: You cannot divide by zero.")
      except ValueError:
          print("Error: Invalid input. Please enter a number.")
     

    2. Using else

      try:
          num = int(input("Enter a number: "))
          result = 10 / num
      except ZeroDivisionError:
          print("Error: You cannot divide by zero.")
      else:
          print(f"Result: {result}")
     

    3. Using finally

      try:
          file = open("example.txt", "r")
          content = file.read()
          print(content)
      except FileNotFoundError:
          print("Error: File not found.")
      finally:
          print("Execution completed, cleaning up...")
     

    4. Raising Exceptions

      def check_positive(number):
      if number < 0:
              raise ValueError("The number must be positive.")
          return number
    
      try:
          print(check_positive(-5))
      except ValueError as e:
          print(f"Error: {e}")

    5. Creating Custom Exceptions

      class CustomError(Exception):
          pass
    
      def check_condition(value):
          if value != "expected":
              raise CustomError("Unexpected value provided!")
    
      try:
          check_condition("unexpected")
      except CustomError as e:
          print(f"Caught a custom exception: {e}")
     

    Explanation of Each Block

    • try: Protects the code that might cause an exception.
    • except: Specifies how to handle specific exceptions.
    • else: Executes if no exceptions are raised in the try block.
    • finally: Ensures that clean-up code runs, like closing files or releasing resources.

    • Best Practices

      • Be specific in exception handling to avoid masking unintended errors.
          except (ValueError, TypeError):  # Catch specific exceptions
        
      • Avoid using a bare except: as it catches all exceptions, including SystemExit and KeyboardInterrupt.
      • Always clean up resources using finally or context managers.
          with open("example.txt", "r") as file:
            content = file.read()
        

      By mastering error handling, you can make your Python programs more robust and user-friendly!

Previous