Built-in Error Types in Python
1. SyntaxError:
- Description: This error occurs when the Python interpreter encounters a syntax mistake in the code.
- Example:
python# Incorrect syntax
print("Hello World"
- Explanation: In the above example, a SyntaxError will be raised because the closing parenthesis is missing in the print statement.
2. IndentationError:
- Description: This error occurs when there is an issue with the indentation of the code.
- Example:
python# Incorrect indentation
def my_function():
print("Indented incorrectly")
- Explanation: The IndentationError will be raised because the 'print' statement inside the function is not indented correctly.
3. NameError:
- Description: This error occurs when a variable or a function name is used before it's defined or in a different scope.
- Example:
python# NameError
print(x)
- Explanation: The NameError will be raised as the variable 'x' is not defined before its usage.
4. TypeError:
- Description: This error occurs when an operation is performed on an object of an inappropriate type.
- Example:
python# TypeError
num = "10"
sum = num + 5
- Explanation: The TypeError will be raised because you cannot add a string and an integer directly.
5. IndexError:
- Description: This error occurs when an index is out of range for a sequence (e.g., list, tuple, string).
- Example:
python# IndexError
my_list = [1, 2, 3]
print(my_list[3])
- Explanation: The IndexError will be raised as the index '3' is out of range for the list 'my_list'.
6. KeyError:
- Description: This error occurs when a dictionary key is not found in the dictionary.
- Example:
python# KeyError
my_dict = {'name': 'John', 'age': 30}
print(my_dict['gender'])
- Explanation: The KeyError will be raised as the key 'gender' does not exist in the dictionary 'my_dict'.
7. ValueError:
- Description: This error occurs when a function receives an argument of the correct type but an inappropriate value.
- Example:
python# ValueError
num = int("hello")
- Explanation: The ValueError will be raised as the string "hello" cannot be converted to an integer.
8. ZeroDivisionError:
- Description: This error occurs when attempting to divide by zero.
- Example:
python# ZeroDivisionError
result = 10 / 0
- Explanation: The ZeroDivisionError will be raised because dividing by zero is not allowed in Python.
These are some of the commonly encountered built-in error types in Python and their explanations with example code. Proper handling of these errors in your code will ensure smoother execution and better debugging.
0 Comments