-
1. Introduction to Python
-
2. Python Basics
-
3. Working with Data Structures
-
4. Functions and Modules
-
5. Object-Oriented Programming (OOP)
-
6. File Handling
-
7. Error and Exception Handling
-
8. Python for Data Analysis
-
9. Advanced Topics in Python
-
10. Working with APIs
-
11. Python for Automation
-
12. Capstone Projects
- 13. Final Assessment and Quizzes
7.1.1 Common exceptions in Python
Python has a wide variety of built-in exceptions, each of which indicates a specific type of error that can occur during the execution of a program. Below are some of the most common exceptions you might encounter:
1. ZeroDivisionError
- Description: Raised when a division or modulo operation is performed with zero as the divisor.
- Example:
x = 10 / 0 # ZeroDivisionError: division by zero
2. ValueError
- Description: Raised when a function receives an argument of the correct type but an inappropriate value, such as passing a string to a function that expects an integer.
- Example:
x = int("hello") # ValueError: invalid literal for int() with base 10: 'hello'
3. IndexError
- Description: Raised when trying to access an element in a list (or other sequence) using an index that is out of range.
- Example:
lst = [1, 2, 3] print(lst[5]) # IndexError: list index out of range
4. TypeError
- Description: Raised when an operation or function is applied to an object of inappropriate type. For example, trying to add a string to an integer.
- Example:
x = "Hello" + 10 # TypeError: can only concatenate str (not "int") to str
5. FileNotFoundError
- Description: Raised when attempting to open a file that does not exist.
- Example:
file = open("non_existent_file.txt", "r") # FileNotFoundError: [Errno 2] No such file or directory: 'non_existent_file.txt'
6. KeyError
- Description: Raised when a dictionary is accessed with a key that does not exist.
- Example:
my_dict = {"name": "John"} print(my_dict["age"]) # KeyError: 'age'
7. AttributeError
- Description: Raised when an attribute reference or assignment fails, usually when you try to access an attribute that doesn't exist in an object.
- Example:
x = 10 x.append(5) # AttributeError: 'int' object has no attribute 'append'
8. ImportError
- Description: Raised when an import statement has issues, such as attempting to import a module or function that doesn't exist.
- Example:
import non_existent_module # ImportError: No module named 'non_existent_module'
9. MemoryError
- Description: Raised when an operation runs out of memory.
- Example:
lst = [0] * (10**10) # MemoryError
10. OverflowError
- Description: Raised when the result of an arithmetic operation is too large to be represented within the allowed range for a numeric type.
- Example:
import math print(math.exp(1000)) # OverflowError: math range error
11. StopIteration
- Description: Raised by the next() function when there are no more items in an iterator to return.
- Example:
it = iter([1, 2, 3]) print(next(it)) # 1 print(next(it)) # 2 print(next(it)) # 3 print(next(it)) # StopIteration
12. RuntimeError
- Description: A generic error that is raised when an error is detected that doesn't fall into a specific category.
- Example:
raise RuntimeError("Something went wrong!") # RuntimeError: Something went wrong!
13. NotImplementedError
- Description: Raised when an abstract method (or method not yet implemented) is called in a class or interface.
- Example:
class MyClass: def my_method(self): raise NotImplementedError("Subclasses should implement this method.") obj = MyClass() obj.my_method() # NotImplementedError: Subclasses should implement this method.
14. PermissionError
- Description: Raised when trying to perform an operation that the user does not have permission to execute, such as opening a file for writing without the proper permissions.
- Example:
file = open("/root/secret.txt", "w") # PermissionError: [Errno 13] Permission denied: '/root/secret.txt'
Handling Common Exceptions
Python provides built-in ways to handle these exceptions using the try and except blocks. Here's an example that handles a ValueError and a ZeroDivisionError:
try: num = int(input("Enter a number: ")) result = 10 / num except ValueError: print("Invalid input. Please enter a valid number.") except ZeroDivisionError: print("Cannot divide by zero!")
By understanding and handling common exceptions, you can ensure that your program is robust and does not crash unexpectedly.
Commenting is not enabled on this course.