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(5raises 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 = craises NameError ifcisn'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 if4isn't in the list. - IndexError: Raised when accessing an index beyond the size of a list.
- Code:
mylist[4]raises IndexError ifmylisthas fewer than 5 elements. - KeyError: Raised when trying to access a missing key in a dictionary.
- Code:
mydict['age']raises KeyError ifageisn't a key.
Raising Exceptions
- Use
raisekeyword 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 ifxis not greater than 0.
- Use