In Python, each instance is required to be a member of a class that derives from Base Exception. Although they may have the same name, two exception classes that do not have a subclassing relationship are never considered equal. The interpreter or the built-in functions may generate the built-in exceptions.
When errors occur, various built-in exceptions in Python are triggered. Python provides a range of built-in exceptions that you can consistently raise and handle within any code. Below are some of the most commonly encountered built-in exceptions:
1. BaseException
In Python, the core class that serves as the basis for all exceptions is referred to as BaseException. This built-in class acts as the parent for every other exception class found in the Python Standard Library. It provides the essential structure for all types of exceptions and lays the groundwork for creating custom exceptions.
The following are some of the characteristics and methods of BaseException:
- args: A tuple of all arguments that were given to the exception when it was raised.
- withtraceback: A method called traceback enables you to add a traceback to an error.
- str: A function that delivers the exception as a string is called str.
Python BaseException Exception Example
To illustrate the BaseException Exception in Python, let's consider an example.
# Python program for Base Exception
class CustomException(BaseException):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
raise CustomException("This is a custom exception.")
Output:
CustomException Traceback ( most recent call last )
Input In [ 1 ], in < cell line : 8>( )
5 def __str__( self ) :
6 return self.message
---- > 8 raise CustomException(" This is a custom exception. ")
CustomException : This is a custom exception.
2. exception Exception
All exceptions in Python are derived from a fundamental class known as Exception. This class acts as the base for all other built-in exceptions within the language. If you want to create your own custom exception, you can extend the Exception class. This design choice allows for the easy management of your custom exception in a manner similar to that of built-in exceptions. It is advisable that all exceptions defined by users should be subclasses of this class.
Python exception Exception Example
Let’s consider an example to illustrate the Exception class in Python.
# Python program for exception Exception
class MyException(Exception):
pass
try:
raise MyException(" This is a custom exception. ")
except MyException as e:
print(" A custom exception was raised : ", e)
Output:
A custom exception was raised : This is a custom exception.
3. AttributeError
This exception is raised whenever there is a failure in an attribute reference or assignment. It typically occurs when you try to access a property or method that does not exist on an object.
Python AttributeError Exception Example
Let's consider an example to illustrate the AttributeError Exception in Python.
# Python program for Attribute Error
class MyClass:
pass
obj = MyClass()
try:
print(obj.non_existent_attribute)
except AttributeError as e:
print(" An attribute error occurred : ", e)
Output:
An attribute error occurred : ' MyClass ' object has no attribute ' non_existent_attribute '
4. TypeError
In Python, when a function or action is applied to an object that is of an inappropriate type, a TypeError exception is raised. This situation commonly arises when you try to invoke a function using the wrong type of argument or when you perform an operation on an object that does not match the expected type.
Python TypeError Exception Example
To illustrate the TypeError Exception in Python, let's consider an example.
# Python program for Type Error
try:
result = "10" + 10
except TypeError as e:
print(" A type error occurred : ", e)
Output:
A type error occurred : can only concatenate str (not " int ") to str
5. ValueError
In Python, the ValueError exception is raised when an argument passed to a built-in method or function has the appropriate type but contains an incorrect value, particularly when there is no other exception that more accurately characterizes the situation.
Python ValueError Exception Example
To illustrate the ValueError Exception in Python, let us consider a specific example.
# Python program for Value Error
try:
int(" a ")
except ValueError as e:
print(" A value error occurred : ", e)
Output:
A value error occurred : invalid literal for int() with base 10 : ' a '
6. KeyError
In Python, when a lookup is performed on a dictionary using a key that is not present, a KeyError exception is raised.
Python KeyError Exception Example
Let's consider an example to illustrate the KeyError Exception in Python.
# Python program for Key Error
my_dict = {' a ': 1, ' b ' : 2}
try:
value = my_dict[' c ']
except KeyError as e:
print(" A key error occurred : ", e)
Output:
A key error occurred : ' c '
7. IndexError
This exception occurs when an index falls outside the valid range. In Python, when an attempt is made to access a list using an index that exceeds its boundaries, the IndexError exception is triggered.
Python IndexError Exception Example
To illustrate the IndexError Exception in Python, let us consider a specific example.
# Python program for Index Error
my_list = [1, 2, 3]
try:
value = my_list[3]
except IndexError as e:
print(" An index error occurred : ", e)
Output:
An index error occurred : list index out of range
8. FileNotFoundError
This exception is triggered when a request is made for a file or directory that cannot be found. When Python attempts to read, access, or retrieve a file that is absent, it raises the FileNotFoundError exception.
Python FileNotFoundError Exception Example
To illustrate the FileNotFound Exception in Python, let’s consider an example.
# Python program for FileNotFoundError
try:
with open(" myfile.txt ") as f:
contents = f.read()
except FileNotFoundError as e:
print(" A file not found error occurred : ", e)
Output:
A file not found error occurred: [ Errno 2 ] No such file or directory : ' myfile.txt '
9. ImportError
This exception occurs when there is a failure in an import statement. In Python, the ImportError exception is activated whenever a specific package or module cannot be imported successfully.
Python ImportError Exception Example
# Python program for Import Error
try:
import nonexistent_module
except ImportError as e:
print(" An import error occurred : ", e)
Output:
An import error occurred : No module named ' nonexistent_module '
10. ArithmeticError
In Python, an ArithmeticError exception is raised whenever an arithmetic operation encounters a failure, such as attempting to divide by zero or calculating the square root of a negative number. This exception serves as the base class for more specific arithmetic errors, including OverflowError and ZeroDivisionError.
Python AirthmeticError Exception Example
Let’s consider an example to illustrate the ArithmeticError Exception in Python.
# Python program for Arithmetic Error
try:
result = 1/0
except ArithmeticError as e:
print(" An arithmetic error occurred : ", e)
Output:
An arithmetic error occurred : division by zero
11. OverflowError
In cases where an arithmetic calculation results in a value that surpasses the maximum limit for representation, Python generates an OverflowError exception. This exception, which is a subclass of ArithmeticError, occurs when the result of a mathematical function exceeds the largest integer that can be represented.
Python OverflowError Exception Example
# Python program for Overflow Error
try:
result = 10 ** 100000
except OverflowError as e:
print(" An overflow error occurred : ", e)
12. SyntaxError
When the Python interpreter detects a syntax problem in your code, it raises the built-in exception known as SyntaxError. A syntax error occurs when the code breaches the syntax rules of the Python programming language. This can happen in various scenarios, such as improper usage of reserved keywords, incorrect indentation, or mistakes with quotation marks.
Python SyntaxError Exception Example
Let’s consider an example to illustrate the SyntaxError Exception in Python.
# Python program for Syntax Error
x = 5
if x > 10
print(" x is greater than 10 ")
Output:
SyntaxError : invalid syntax
13. AssertionError
When an assert statement fails, Python raises a built-in exception referred to as AssertionError. The assert statement is utilized to check for conditions that must hold true for the program to continue executing. If the condition specified in the assert statement evaluates to false, an AssertionError exception is triggered.
Python AssertionError Exception Example
Let's consider an example to illustrate the AssertionError Exception in Python.
# Python program for Assertion Error
x = 5
assert x > 10, " x is not greater than 10 "
Output:
AssertionError: x is not greater than 10
14. FloatingPointError
In Python, the FloatingPointError exception is activated whenever an operation involving floating-point numbers results in an undefined or nonsensical mathematical outcome. This may occur in instances such as performing a division by zero or when a value is either excessively large or too small to be represented as a floating-point number.
Python FloatingPointError Exception Example
Let's consider an example to illustrate the FloatingPointError Exception in Python.
# Python program for FloatingPointError
x = float(' inf ')
y = x / x
print(y)
Output:
15. EOFError
In instances where the end-of-file (EOF) indicator is reached and no additional data can be accessed, Python raises its built-in EOFError exception. This situation can arise when you are attempting to read from a file, a socket, or any other form of input stream.
Python EOFError Exception Example
To illustrate the EOFError Exception in Python, let’s consider a practical example.
# Python program for EOFError
try:
file = open(" example.txt ", " r ")
for line in file:
print(line)
file.read()
except EOFError:
print(" Reached end of file. ")
finally:
file.close()
Output:
EOFError : EOF when reading a line
Python Example to Demonstrate Several Built-in Exceptions
Below is an illustration that showcases the process of raising and managing various built-in exceptions:
# Python program for demonstrating and handling Built in Excpetions
try:
a = [ 1, 2, 3 ]
print(a[ 3 ])
except IndexError as e:
print(" An index error occurred : ", e)
try:
b = 5
print(b / 0)
except ZeroDivisionError as e:
print(" A division by zero error occurred : ", e)
try:
c = " hello "
d = int(c)
except ValueError as e:
print(" A value error occurred : ", e)
Output:
An index error occurred : list index out of range
A division by zero error occurred: division by zero
A value error occurred : invalid literal for int( ) with base 10 : ' hello '
In this illustration, the initial try block throws an IndexError exception, which is subsequently captured and managed by the corresponding except block. The following try block generates a ZeroDivisionError exception, which is similarly intercepted and dealt with by the except block. Lastly, the third try block raises a ValueError exception, which is again caught and addressed by the except block.
This illustrates the process of raising and managing various built-in exceptions in Python, as well as crafting dedicated exception handlers tailored to each exception type. Through the implementation of exception handling, you can develop resilient code that adeptly addresses errors and exceptions, while also delivering informative error messages to the user.