Python Built-in Exceptions

Python Built-in Exceptions

Python is a versatile and powerful programming language that provides a wide range of built-in exceptions to handle various types of errors and exceptions that may occur during program execution. These exceptions help developers identify and resolve issues, making their code more robust and reliable.

1. ValueError

The ValueError exception is raised when a function receives an argument of the correct type but an inappropriate value. For example, if we try to convert a string that does not represent a valid integer using the int() function, a ValueError will be raised. Let’s take a look at an example:

“`python
def convert_to_integer(string):
try:
result = int(string)
print(“Conversion successful. Result:”, result)
except ValueError:
print(“Invalid input. Please provide a valid integer.”)

convert_to_integer(“123”) # Output: Conversion successful. Result: 123
convert_to_integer(“abc”) # Output: Invalid input. Please provide a valid integer.
“`

In the above example, the first function call successfully converts the string “123” to an integer, while the second function call raises a ValueError because “abc” cannot be converted to an integer.

2. FileNotFoundError

The FileNotFoundError exception is raised when a file or directory is requested but cannot be found. This can occur when trying to open a file that does not exist or when trying to access a directory that has been deleted. Here’s an example:

“`python
try:
file = open(“nonexistent_file.txt”, “r”)
print(“File found.”)
except FileNotFoundError:
print(“File not found. Please check the file path.”)
“`

In the above example, the code tries to open a file called “nonexistent_file.txt” in read mode. Since the file does not exist, a FileNotFoundError exception is raised, and the corresponding error message is displayed.

3. IndexError

The IndexError exception is raised when trying to access an index that is out of range in a sequence, such as a list or a string. For example:

“`python
my_list = [1, 2, 3]

try:
print(my_list[3])
except IndexError:
print(“Index out of range. Please provide a valid index.”)
“`

In the above example, the code tries to access the element at index 3 in the list, which does not exist. As a result, an IndexError exception is raised, and the error message is displayed.

4. TypeError

The TypeError exception is raised when an operation or function is applied to an object of an inappropriate type. For instance, if we try to concatenate a string and an integer without converting the integer to a string, a TypeError will be raised. Here’s an example:

“`python
string = “Hello”
number = 123

try:
result = string + number
print(“Concatenation successful. Result:”, result)
except TypeError:
print(“Invalid operation. Please provide objects of compatible types.”)
“`

In the above example, the code tries to concatenate a string and an integer without converting the integer to a string. As a result, a TypeError exception is raised, and the error message is displayed.

5. ZeroDivisionError

The ZeroDivisionError exception is raised when trying to divide a number by zero. This commonly occurs when a program attempts to perform a division operation without checking for a zero divisor. Here’s an example:

“`python
try:
result = 10 / 0
print(“Division successful. Result:”, result)
except ZeroDivisionError:
print(“Invalid operation. Cannot divide by zero.”)
“`

In the above example, the code tries to divide the number 10 by zero. Since dividing by zero is undefined, a ZeroDivisionError exception is raised, and the error message is displayed.

Conclusion

Python’s built-in exceptions provide a convenient way to handle errors and exceptions that may occur during program execution. By using these exceptions and appropriate error-handling techniques, developers can create more robust and reliable code. Understanding and utilizing these exceptions will help you write better Python programs and easily identify and resolve issues that may arise.

Scroll to Top