Python Exceptions List 🎯

beginner
8 min

Python Exceptions List 🎯

Welcome to our comprehensive guide on Python Exceptions! This tutorial is designed for beginners and intermediates, covering the fundamentals and advanced aspects of Python exceptions. Let's dive in!

What are Exceptions in Python? 📝

Exceptions are events that occur during the execution of a program that interrupt its normal flow. In Python, these events are handled as exceptions, which are objects of the Exception class or its subclasses.

Why use Exceptions? 💡

Exceptions help us to handle errors gracefully, providing a way to handle and recover from unexpected situations. They make our programs more robust, error-tolerant, and easier to debug.

Basic Python Exceptions 📝

1. NameError

Occurs when you try to use a variable that hasn't been defined.

python
print(undeclared_var) # Raises NameError

2. TypeError

Occurs when an operation or function is applied to an object of inappropriate type.

python
'2' + 3 # Raises TypeError

3. ZeroDivisionError

Occurs when you try to divide by zero.

python
1 / 0 # Raises ZeroDivisionError

Custom Exceptions 💡

You can create your own exceptions by creating a new class that inherits from the Exception class.

python
class MyCustomException(Exception): pass def divide(a, b): if b == 0: raise MyCustomException("Cannot divide by zero") try: divide(10, 0) except MyCustomException as e: print(e)

Exception Handling 📝

Exception handling is done using try, except, and finally blocks.

python
try: # Code block where exceptions may occur except ExceptionType: # Code block that handles the exception finally: # Code block that always executes, regardless of exceptions

Exception Chaining 💡

You can chain exceptions, meaning an exception can raise another exception.

python
class MyCustomException(Exception): def __init__(self, message): super().__init__(message) self.message = message def divide(a, b): if b == 0: raise MyCustomException("Cannot divide by zero") try: divide(10, 0) except MyCustomException as e: raise ValueError(f"{e.message}, please provide a different number.")

Quiz 📝

Quick Quiz
Question 1 of 1

What exception is raised when you try to divide by zero in Python?

That's it for our Python Exceptions lesson! With practice, you'll master handling errors in your Python programs. Happy coding! 💻🌟