Python - Built-in Exceptions
When writing Python programs, errors can occur during execution due to invalid operations, wrong input, missing files, or unexpected conditions.
To handle these situations, Python provides a wide range of built-in exceptions.
Built-in exceptions are predefined error classes that automatically get raised when a problem occurs in your program.
Understanding these exceptions is essential for writing stable, error-free, and professional Python applications.
What are Built-in Exceptions in Python?
Built-in exceptions are standard error types provided by Python.
They are automatically raised when Python encounters an error during execution.
Example:
print(10 / 0)Output:
ZeroDivisionError: division by zeroHere, Python automatically raises a built-in exception.
Why Built-in Exceptions are Important?
Built-in exceptions help developers:
- Identify errors quickly
- Debug programs efficiently
- Handle runtime issues properly
- Improve application stability
- Write professional-grade code
Common Python Built-in Exceptions
Python provides many built-in exceptions. Below are the most commonly used ones.
1. ZeroDivisionError
Occurs when dividing a number by zero.
print(10 / 0)Output:
ZeroDivisionError: division by zero2. ValueError
Occurs when a function receives an invalid value.
int("abc")Output:
ValueError: invalid literal for int()3. TypeError
Occurs when an operation is performed on incompatible data types.
"10" + 5Output:
TypeError: can only concatenate str (not "int") to str4. IndexError
Occurs when accessing an invalid index in a list or tuple.
numbers = [1, 2, 3]
print(numbers[5])Output:
IndexError: list index out of range5. KeyError
Occurs when accessing a missing dictionary key.
data = {"name": "John"}
print(data["age"])Output:
KeyError: 'age'6. FileNotFoundError
Occurs when a file does not exist.
open("missing_file.txt")Output:
FileNotFoundError: No such file or directory7. AttributeError
Occurs when an invalid attribute is accessed.
x = 10
x.append(5)Output:
AttributeError: 'int' object has no attribute 'append'8. ImportError
Occurs when a module cannot be imported.
import non_existing_moduleOutput:
ImportError: No module named 'non_existing_module'9. NameError
Occurs when using an undefined variable.
print(value)Output:
NameError: name 'value' is not defined10. OverflowError
Occurs when a numeric value exceeds limit.
import math
print(math.exp(1000))Output:
OverflowError: math range errorList of Common Built-in Exceptions
| Exception | Description |
|---|---|
| ZeroDivisionError | Division by zero |
| ValueError | Invalid value |
| TypeError | Wrong data type |
| IndexError | Invalid index |
| KeyError | Missing dictionary key |
| FileNotFoundError | File not found |
| AttributeError | Invalid attribute |
| ImportError | Module import failure |
| NameError | Undefined variable |
| OverflowError | Numeric overflow |
Handling Built-in Exceptions
You can handle built-in exceptions using try-except.
Example: Handling ValueError
try:
num = int("abc")
except ValueError:
print("Invalid input!")Output:
Invalid input!Example: Handling Multiple Exceptions
try:
x = 10 / 0
except (ZeroDivisionError, ValueError):
print("An error occurred")Example: Generic Exception Handling
try:
print(undefined_variable)
except Exception as e:
print("Error:", e)Why Learn Built-in Exceptions?
Understanding built-in exceptions helps you:
- Debug faster
- Write safer code
- Improve error handling
- Build reliable applications
- Avoid unexpected crashes
Best Practices
1. Use Specific Exceptions
Good:
except ValueError:Bad:
except Exception:2. Do Not Ignore Errors
Bad:
try:
risky_code()
except:
pass3. Use try-except Properly
Handle only expected errors.
4. Learn Common Exceptions
Focus on frequently used ones like:
- ValueError
- TypeError
- IndexError
- KeyError
Common Mistakes
Catching All Exceptions
Avoid masking real issues.
Ignoring Error Messages
Always inspect exception details.
Using Wrong Exception Type
Choose correct exception for clarity.
Real-World Applications
Built-in exceptions are used in:
- Web applications (Django, Flask)
- APIs and backend systems
- Data processing pipelines
- File handling systems
- Banking applications
- Machine learning pipelines
- Automation scripts
Summary
Python built-in exceptions are predefined error types that help detect and handle runtime errors effectively. They are essential for debugging and writing reliable programs.
Key Takeaways
- Built-in exceptions are predefined in Python
- They are automatically raised during errors
- Common types include ValueError, TypeError, IndexError, etc.
- Use try-except to handle them
- Always prefer specific exceptions
- Essential for professional Python development
Mastering built-in exceptions is a key step toward writing robust, production-ready Python applications.


0 Comments