About Lesson
Types of Exceptions
Built-in Exceptions
- Definition: Built-in exceptions are predefined errors in Python that are raised when the interpreter encounters an error during execution.
- Common Built-in Exceptions:
ZeroDivisionError
: Raised when division by zero is attempted. pythonprint(10 / 0) # Raises ZeroDivisionError
IndexError
: Raised when trying to access an index that is out of range. pythonmy_list = [1, 2, 3] print(my_list[5]) # Raises IndexError
KeyError
: Raised when trying to access a key that does not exist in a dictionary. pythonmy_dict = {'name': 'Alice'} print(my_dict['age']) # Raises KeyError
TypeError
: Raised when an operation or function is applied to an object of inappropriate type. pythonprint("Hello" + 5) # Raises TypeError
Custom Exceptions
- Definition: Custom exceptions are user-defined errors that can be created to handle specific situations in a program.
- Creating Custom Exceptions: python
class CustomError(Exception): pass def check_value(value): if value < 0: raise CustomError("Value cannot be negative") try: check_value(-1) except CustomError as e: print(e) # Output: Value cannot be negative
- Try-Except-Finally
- Raising exceptions