Skip to main content

Errors and Exceptions

適用實例:

  • A file doesn’t exist

  • A network or database connection fails

  • Your code receives invalid input

錯誤類型:

    FileNotFoundError : The file might not exist IndexError : The file might not have enough lines of data ValueError : The data in the file might not be convertible to integers ZeroDivisionError : The second number might be zero

    Try-Except

    • except OSError 
    def character_frequency(filename):
      """Counts the frequency of each character in the given file."""
      # First try to open the file
      try:
        f = open(filename)
      except OSError:
        return None
    
      # Now process the file
      characters = {}
      for line in f:
        for char in line:
          characters[char] = characters.get(char, 0) + 1
      f.close() 
      return characters

    Raise

    • raise ValueError("Some custom error messages") 
    def validate_user(username, minlen):
      assert type(username) == str, "username must be a string"
      if minlen < 1:
        raise ValueError("minlen must be at least 1")
    
      if len(username) < minlen:
        return False
      if not username.isalnum():
        return False
      return True

    For unit test

    • .assertRaises() 
    import unittest
    
    from validations import validate_user
    
    class TestValidateUser(unittest.TestCase):
      def test_valid(self):
        self.assertEqual(validate_user("validuser", 3), True)
    
      def test_too_short(self):
        self.assertEqual(validate_user("inv", 5), False)
    
      def test_invalid_characters(self):
        self.assertEqual(validate_user("invalid_user", 1), False)
        
      def test_invalid_minlen(self):
        self.assertRaises(ValueError, validate_user, "user", -1)
    
    
    # Run the tests
    unittest.main()
      FileNotFoundError : The file might not exist IndexError : The file might not have enough lines of data ValueError : The data in the file might not be convertible to integers ZeroDivisionError : The second number might be zero
      def enhanced_read_and_divide(filename):
      	try:
      		with open(filename, 'r') as file:
      			data = file.readlines()
             	 
              # Ensure there are at least two lines in the file
              if len(data) < 2:
                  raise ValueError("Not enough data in the file.")
             	 
              num1 = int(data[0])
              num2 = int(data[1])
             	 
              # Check if second number is zero
              if num2 == 0:
                  raise ZeroDivisionError("The denominator is zero.")
             	 
              return num1 / num2
      
      
      	except FileNotFoundError:
          	     return "Error: The file was not found."
      	except ValueError as ve:
          	     return f"Value error: {ve}"
      	except ZeroDivisionError as zde:
          	     return f"Division error: {zde}"