Key Concepts in Syntax Errors and Exceptions

  • Syntax Error

    • Occurs when the parser detects an invalid statement.
    • Example: Missing new line or mismatched parentheses.
    • Code: a = 5 print(a) raises a syntax error.
    • Code with parentheses: print(5 raises a syntax error due to missing ).
  • Exception

    • Occurs during execution even if the syntax is correct.
    • Example: Adding incompatible types.
    • Code: a = 5 + '10' raises a TypeError.
  • Common Built-in Exceptions

    • ModuleNotFoundError: Raised when trying to import a non-existent module.
    • NameError: Raised when referencing a variable that hasn't been defined.
    • Code: b = c raises NameError if c isn't defined.
    • FileNotFoundError: Raised when trying to open a non-existent file.
    • Code: f = open('somefile.txt') raises FileNotFoundError.
    • ValueError: Raised when a function receives an argument with the right type but inappropriate value.
    • Code: a.remove(4) raises ValueError if 4 isn't in the list.
    • IndexError: Raised when accessing an index beyond the size of a list.
    • Code: mylist[4] raises IndexError if mylist has fewer than 5 elements.
    • KeyError: Raised when trying to access a missing key in a dictionary.
    • Code: mydict['age'] raises KeyError if age isn't a key.
  • Raising Exceptions

    • Use raise keyword to trigger an exception.
    • Example:
      python x = -5 if x < 0: raise Exception('x should be positive')
    • Using assert Statement
    • Use for conditional checks that will raise an AssertionError if the condition fails.
    • Example: assert x > 0, "x must be positive" raises AssertionError if x is not greater than 0.