
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why are Python exceptions named \\\"Error\\\" (e.g. ZeroDivisionError, NameError, TypeError)?
In Python, exception names usually end with "Error" (like ZeroDivisionError, NameError, and TypeError). This clearly shows that they are related to problems that happen while the program is running. Using this naming style makes error messages easier to read, helps with debugging.
Why exceptions end with "Error"
An exception is a kind of (run-time) error. Having the word "Error" in the name of the exception may help us realize that there is an issue when we encounter an exception. It follows a logical naming convention similar to other programming languages like Java and C++, that also use names ending in "Error" or "Exception".
Example: ZeroDivisionError
In the following example, we are dividing a number by zero, which causes Python to raise a ZeroDivisionError -
try: result = 10 / 0 except ZeroDivisionError as e: print("Caught an error:", e)
We get the following output -
Caught an error: division by zero
Example: NameError
In this example, we try to use a variable that hasn't been defined. Python raises a NameError -
try: print(unknown_variable) except NameError as e: print("Caught an error:", e)
The output is -
Caught an error: name 'unknown_variable' is not defined
Consistency in the Python Standard Library
The Python standard library includes many exceptions that follow this naming convention. This consistency helps you to remember and anticipate exception names easily.
Example: TypeError
In this example, we try to add a number and a string, which results in a TypeError -
try: result = 5 + "five" except TypeError as e: print("Caught an error:", e)
The output is -
Caught an error: unsupported operand type(s) for +: 'int' and 'str'