Python's built-in exceptions are predefined errors that arise during execution, signaling that something went wrong. These include TypeError
, ValueError
, KeyError
, IndexError
, FileNotFoundError
, and many others. Each corresponds to specific error conditions, such as incorrect data type usage, missing keys, or out-of-range indexes, allowing developers to catch and respond to these issues effectively within their code.
Base Classes
The section on "Python Built-in Exceptions" covers various base classes integral to exception handling. These base classes serve as the foundation for all other exception classes in Python. Key base classes include Exception
, which is the parent class for all built-in, non-system-exiting exceptions. ArithmeticError
is another base class for errors in arithmetic operations, such as division by zero. LookupError
serves as the base for exceptions raised when a lookup on a collection fails. Understanding these base classes is crucial for effective error and exception management in Python applications. Each class encapsulates specific types of errors, aiding in precise exception handling and debugging.
exception BaseException
The exception BaseException
serves as the superclass for all built-in exceptions in Python. It is the base class from which all other exception classes are derived. This design allows for a broad catchment of errors and interrupts in a program. Key exceptions like SystemExit, KeyboardInterrupt, and Exception itself inherit from BaseException, ensuring a hierarchical structure that facilitates precise and effective error handling.
For instance, catching BaseException
can intercept almost any exception, including system-exiting ones.
try:
# risky code
except BaseException as error:
print(f"An error occurred: {error}")
However, catching BaseException is generally discouraged except in specific cases, as it can catch system exit signals and other lower-level signals not meant for typical error handling. It's more common to catch Exception, which doesn't include system-exiting exceptions.
exception Exception
The section on "exception Exception" addresses the base class for all built-in exceptions in Python, except for system-exiting exceptions like SystemExit, KeyboardInterrupt, and GeneratorExit, which derive from BaseException directly. This foundational class acts as a catch-all for error handling, enabling programmers to handle a wide array of exceptions that do not fit under more specific exception types.
For instance, custom exceptions typically inherit from the Exception class to integrate smoothly with Python's error handling mechanisms. This strategy allows developers to create flexible, robust error handling structures within their applications.
class MyCustomError(Exception):
"""A custom exception class."""
pass
try:
raise MyCustomError("An error occurred")
except MyCustomError as e:
print(f"Caught an exception: {e}")
In this example, MyCustomError is a user-defined exception class that extends Exception, demonstrating how to define and handle custom exceptions in Python.
exception ArithmeticError
ArithmeticError is a built-in exception in Python that serves as the base class for arithmetic errors. It catches errors like OverflowError, ZeroDivisionError, and FloatingPointError for arithmetic or numeric operations. This hierarchical design allows the handling of specific arithmetic issues under a broad category.
For instance, attempting to divide by zero raises a ZeroDivisionError, a subclass of ArithmeticError.
try:
result = 1 / 0
except ArithmeticError:
print("Arithmetic problem encountered.")
In this code, dividing by zero triggers an ArithmeticError, and the program prints a message instead of terminating unexpectedly. This demonstrates handling arithmetic exceptions to ensure robustness in Python applications.
exception BufferError
The BufferError exception in Python is a built-in exception raised when a buffer-related operation cannot be performed. This typically occurs in situations involving memory view operations or when trying to directly manipulate buffers.
For example, attempting to release a buffer that is already released can trigger a BufferError. This exception ensures data integrity in memory buffers by preventing operations that could lead to inconsistent or undefined states.
import numpy as np
# Creating a numpy array
arr = np.array([1, 2, 3])
# Getting the memory buffer view of the array
buffer = memoryview(arr)
# Releasing the buffer
buffer.release()
# Attempting to release the buffer again raises BufferError
try:
buffer.release()
except BufferError:
print("Cannot release a buffer that is already released.")
This code snippet demonstrates the safe handling of code.
Base Classes
The section on "Python Built-in Exceptions" covers various base classes integral to exception handling. These base classes serve as the foundation for all other exception classes in Python. Key base classes include Exception
, which is the parent class for all built-in, non-system-exiting exceptions. ArithmeticError
is another base class for errors in arithmetic operations, such as division by zero. LookupError
serves as the base for exceptions raised when a lookup on a collection fails. Understanding these base classes is crucial for effective error and exception management in Python applications. Each class encapsulates specific types of errors, aiding in precise exception handling and debugging.
exception BaseException
The exception BaseException
serves as the superclass for all built-in exceptions in Python. It is the base class from which all other exception classes are derived. This design allows for a broad catchment of errors and interrupts in a program. Key exceptions like SystemExit
, KeyboardInterrupt
, and Exception
itself inherit from BaseException
, ensuring a hierarchical structure that facilitates precise and effective error handling.
For instance, catching BaseException
can intercept almost any exception, including system-exiting ones.
try:
# risky code
except BaseException as error:
print(f"An error occurred: {error}")
However, catching BaseException
is generally discouraged except in specific cases, as it can catch system exit signals and other lower-level signals not meant for typical error handling. It's more common to catch Exception
, which doesn't include system-exiting exceptions.
exception Exception
The section on "exception Exception" addresses the base class for all built-in exceptions in Python, except for system-exiting exceptions like SystemExit
, KeyboardInterrupt
, and GeneratorExit
, which derive from BaseException
directly. This foundational class acts as a catch-all for error handling, enabling programmers to handle a wide array of exceptions that do not fit under more specific exception types.
For instance, custom exceptions typically inherit from the Exception
class to integrate smoothly with Python's error handling mechanisms. This strategy allows developers to create flexible, robust error handling structures within their applications.
class MyCustomError(Exception):
"""A custom exception class."""
pass
try:
raise MyCustomError("An error occurred")
except MyCustomError as e:
print(f"Caught an exception: {e}")
In this example, MyCustomError
is a user-defined exception class that extends Exception
, demonstrating how to define and handle custom exceptions in Python.
exception ArithmeticError
ArithmeticError
is a built-in exception in Python that serves as the base class for arithmetic errors. It catches errors like OverflowError
, ZeroDivisionError
, and FloatingPointError
for arithmetic or numeric operations. This hierarchical design allows the handling of specific arithmetic issues under a broad category.
For instance, attempting to divide by zero raises a ZeroDivisionError
, a subclass of ArithmeticError
.
try:
result = 1 / 0
except ArithmeticError:
print("Arithmetic problem encountered.")
In this code, dividing by zero triggers an ArithmeticError
, and the program prints a message instead of terminating unexpectedly. This demonstrates handling arithmetic exceptions to ensure robustness in Python applications.
exception BufferError
The BufferError
exception in Python is a built-in exception raised when a buffer-related operation cannot be performed. This typically occurs in situations involving memory view operations or when trying to directly manipulate buffers.
For example, attempting to release a buffer that is already released can trigger a BufferError
. This exception ensures data integrity in memory buffers by preventing operations that could lead to inconsistent or undefined states.
Here's a simple coding example illustrating a scenario where BufferError
might be raised.
import numpy as np
# Creating a numpy array
arr = np.array([1, 2, 3])
# Getting the memory buffer view of the array
buffer = memoryview(arr)
# Releasing the buffer
buffer.release()
# Attempting to release the buffer again raises BufferError
try:
buffer.release()
except BufferError:
print("Cannot release a buffer that is already released.")
This code snippet demonstrates the safe handling of buffer operations, highlighting the importance of managing memory resources correctly in Python applications.
exception LookupError
The LookupError
exception in Python is a built-in exception that acts as the base class for exceptions that occur when a lookup for a key or index fails in a collection. This includes errors like KeyError
, which occurs when a key is not found in a dictionary, and IndexError
, which happens when an index is not found in a list.
For example, accessing a non-existent key in a dictionary will raise a KeyError
.
my_dict = {'a': 1, 'b': 2}
print(my_dict['c']) # Raises KeyError
Similarly, trying to access an out-of-range index in a list will raise an IndexError
.
my_list = [1, 2, 3]
print(my_list[3]) # Raises IndexError
Both KeyError
and IndexError
are specific instances of LookupError
, enabling you to handle these errors with a single exception block if necessary.
Concrete Exceptions
Python Built-in Exceptions encompass a variety of concrete exceptions that handle specific error types encountered during execution. These exceptions are subclasses of the BaseException
class and directly relate to common error scenarios in Python programs.
For instance, the ValueError
exception occurs when a function receives an argument of the correct type but with an inappropriate value. Example: int('abc')
raises a ValueError
because 'abc' cannot convert to an integer.
Similarly, IndexError
is raised when attempting to access an index outside the bounds of a list. For example, accessing the fifth element of a four-item list (my_list[4]
) results in an IndexError
.
Another common exception, KeyError
, occurs when a dictionary is accessed with a key that does not exist. Trying to retrieve a value using a non-existent key (my_dict['nonexistent_key']
) triggers a KeyError
.
TypeError
arises when an operation or function is applied to an object of inappropriate type, such as adding a string to an integer ('hello' + 5
).
These concrete exceptions provide a clear path for developers to diagnose and handle errors, ensuring robust and error-resistant Python applications.
exception AssertionError
The exception AssertionError
in Python is a built-in exception raised when an assert statement fails, indicating that an expression evaluates to False in a context where it was expected to be True. This exception is a key debugging tool used to test conditions that should never occur if the code is correct.
For example, you might use to check if a variable x
is greater than 0.
x = -10
assert x > 0, "x is not greater than 0"
If x
is not greater than 0, Python raises an AssertionError
with the message "x is not greater than 0". This mechanism helps in identifying logical errors early in the development process.
exception AttributeError
The exception AttributeError
in Python is raised when an attribute reference or assignment fails. This typically occurs when trying to access or assign a non-existent attribute of an object, indicating that the object does not possess the specified attribute. This exception is a direct manifestation of Python's dynamic nature, allowing attributes to be added and removed at runtime.
For example, attempting to access a non-existing attribute of an instance triggers AttributeError
.
class MyClass:
def __init__(self):
self.name = "Example"
instance = MyClass()
print(instance.age) # AttributeError: 'MyClass' object has no attribute 'age'
Similarly, trying to assign a value to a read-only attribute can also raise an AttributeError
.
class MyClass:
@property
def name(self):
return "Read-Only Name"
instance = MyClass()
instance.name = "New Name" # AttributeError: can't set attribute
Handling AttributeError
allows programs to react gracefully to missing attributes, enhancing robustness and user experience.
exception EOFError
The exception EOFError
is one of the Python Built-in Exceptions. It occurs when the input()
function hits an end-of-file condition (EOF) without reading any data. This usually happens when a user inputs an EOF signal (Ctrl+D on Unix/Linux or Ctrl+Z on Windows) or when input()
is called in a non-interactive setting, such as reading from a pipe or a redirect, and there's no more data to read.
Handling EOFError
ensures that your program can gracefully respond to unexpected EOF signals. For instance:
try:
user_input = input("Enter something: ")
except EOFError:
print("EOF encountered. Exiting program.")
else:
print(f"You entered: {user_input}")
This code snippet demonstrates catching EOFError
to prevent abrupt termination, allowing for a cleaner exit or alternative actions when encountering EOF.
exception FloatingPointError
The exception FloatingPointError
is a built-in exception in Python that occurs during floating-point operations if the floating point operation fails. This exception is closely related to the floating point arithmetic operations within Python programs. It is a derivative of the ArithmeticError
exception.
For instance, although Python typically handles floating point errors gracefully, enabling the floating point error detection with specific libraries or using external modules can trigger a FloatingPointError
.
Example.
import math
# Attempt to trigger a FloatingPointError (This is more of a conceptual example as Python's default settings prevent FloatingPointError from being raised in most cases)
try:
# This operation might cause a floating point error in a different programming context or with specific Python settings
result = math.exp(1000)
except FloatingPointError:
print("A floating point error occurred.")
else:
print("Operation successful.")
In standard Python usage, encountering a FloatingPointError
is rare because Python and its libraries are designed to handle such errors internally. However, understanding this exception is crucial for developers working with low-level floating point operations or interfacing with C libraries where such errors might be more common.
exception GeneratorExit
The GeneratorExit
exception occurs when a generator or coroutine is closed; it is a built-in exception in Python. This exception is crucial for managing generator termination gracefully. When a generator's close()
method is called, Python raises GeneratorExit
at the point where the generator was paused, allowing it to perform any necessary cleanup actions before stopping.
For example:
def my_generator():
try:
yield 'Starting'
yield 'Running'
except GeneratorExit:
print('Generator is closing')
gen = my_generator()
print(next(gen)) # Outputs: Starting
print(next(gen)) # Outputs: Running
gen.close() # Outputs: Generator is closing
This mechanism ensures resources are released, and the generator stops its execution in an orderly fashion.
exception ImportError
The ImportError
exception in Python occurs when the import statement cannot find the module definition or cannot load a module. This built-in exception is crucial for managing and debugging module dependencies within Python applications. For instance, if a script attempts to import nonexistentmodule
, Python raises an ImportError
, signaling that the specified module does not exist in the module search path.
Example.
try:
import nonexistentmodule
except ImportError:
print("Module not found.")
In this code, Python tries to import a module named nonexistentmodule
. Since this module does not exist, an ImportError
is raised, and the except block is executed, printing "Module not found." This exception handling ensures the program can gracefully handle missing dependencies.
exception ModuleNotFoundError
This is the subclass of ImportError
which is raised by import when a module could not be found. It is also raised when None is found in sys.modules
.
exception IndexError
The exception IndexError
is a built-in exception in Python that occurs when accessing an index that is out of the range of a sequence, such as a list or a tuple. This error signifies that the code has attempted to retrieve an element using an index that exceeds the sequence's current bounds, interrupting the program's execution.
For instance, consider a list my_list = [1, 2, 3]
. Accessing my_list[3]
would raise an IndexError
because index 3 is out of range for a list with only three elements, where the maximum valid index is 2, given that indexing starts at 0 in Python.
Handling an IndexError
can be done using a try-except block. This approach allows the program to gracefully respond to attempts to access invalid indexes:
try:
print(my_list[3])
except IndexError:
print("That index is out of range.")
In this example, instead of the program terminating abruptly with an error, it catches the IndexError
and prints a friendly message, thus maintaining a smooth execution flow.
exception KeyError
The exception KeyError
in Python is a built-in exception raised when a dictionary does not have the specified key. This error highlights an attempt to access a non-existent dictionary element, signaling the absence of the key within the dictionary's existing keys. Handling this exception is crucial in Python coding to ensure the robustness of dictionary operations.
Example.
my_dict = {'a': 1, 'b': 2}
try:
value = my_dict['c']
except KeyError:
print("Key 'c' does not exist in the dictionary.")
In this code snippet, accessing my_dict['c']
raises a KeyError
because 'c' is not a key in my_dict
. The try-except block catches the KeyError
, preventing the program from crashing and instead prints a message indicating the missing key.
exception KeyboardInterrupt
The exception KeyboardInterrupt
is a built-in exception in Python that occurs when the user interrupts the program's execution, typically by pressing Ctrl+C or the delete button. This exception helps in gracefully terminating the program when the user decides to stop its process manually. It is part of Python's core exceptions and allows developers to handle unexpected interruptions, ensuring the program can exit without causing harm to system resources or leaving processes hanging.
For example, to handle a KeyboardInterrupt
exception, you can use a try-except block.
try:
while True:
print("Press Ctrl+C to interrupt")
except KeyboardInterrupt:
print("Program interrupted by the user")
In this code, the program continuously prints a message until the user interrupts it, catching the KeyboardInterrupt
and printing a termination message instead of the default traceback. This demonstrates how to use Python's exception-handling mechanism to manage interruptions smoothly.
exception MemoryError
The MemoryError
exception in Python indicates that an operation ran out of memory. This built-in exception signals that the Python interpreter could not allocate enough memory to perform the specified task. It typically occurs in large-scale data operations or when excessive memory consumption exceeds the system's available resources.
For instance, creating a massive list or array the system cannot accommodate may trigger a MemoryError
. Here's a simplified example.
try:
large_list = [0] * 10**10
except MemoryError:
print("MemoryError: This operation ran out of memory.")
This code attempts to allocate memory for a very large list. If the system does not have enough memory available, it raises a MemoryError
, which is then caught by the except block, preventing the program from crashing and allowing for graceful error handling.
exception NameError
The exception NameError
in Python is a built-in exception when a local or global name is not found. This typically happens when an attempt is made to use a variable or function name that has not been defined within the scope it is being called.
For example, attempting to print a variable that hasn't been declared will raise a NameError
.
print(undeclared_variable)
This results in.
NameError: name 'undeclared_variable' is not found
To handle a NameError
, you can use a try-except block, allowing your program to execute alternative code or provide a user-friendly message when the exception occurs.
try:
print(undeclared_variable)
except NameError:
print("Variable is not defined.")
This approach ensures the program's flow continues, enhancing error management and code robustness.
exception NotImplementedError
The NotImplementedError
exception is a specific Python built-in exception that signals that an abstract method or function requires an implementation in a subclass. It typically indicates that a method or operation is part of an interface or base class design, but needs to be concretely implemented by subclasses to be usable. This exception enforces a contract for derived classes to follow, ensuring they implement all necessary methods.
For example, if you have a base class Shape
with a method area
that is meant to be overridden in subclasses, you can raise NotImplementedError
in the base method.
class Shape:
def area(self):
raise NotImplementedError("Subclass must implement abstract method")
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
Attempting to call the area
method on an instance of Shape
will raise a NotImplementedError
, prompting the developer to implement the method in a subclass like Circle
.
exception OSError([arg])
The OSError
exception in Python occurs when a system-related error is encountered, typically involving file and directory operations. This built-in exception is a base class for several other file-related exceptions such as FileNotFoundError
, PermissionError
, and InterruptedError
, reflecting specific system errors.
Python programs often interact with the operating system's underlying files and directories. When an error occurs during these interactions, Python raises an OSError
. Common causes include attempting to open a non-existent file, lacking the necessary permissions to access a resource, or encountering a broken pipe during communication.
For example, trying to open a file that does not exist will raise an OSError
.
try:
with open('non_existent_file.txt') as file:
read_data = file.read()
except OSError as e:
print(f'Error occurred: {e}')
exception OverflowError
The exception OverflowError
is a built-in exception in Python that signals when an arithmetic operation exceeds the limits of a variable's numerical type, resulting in an overflow. This typically occurs in fixed-size data types, such as in certain integer or floating-point operations that exceed the maximum representable value.
For instance, in Python, while the int
type can handle arbitrarily large numbers, operations that produce a number too large for a specific context (like C longs in extensions) can trigger an OverflowError
. However, it's more commonly seen with floating-point numbers in operations that exceed the range of Python's floating-point representations.
Example.
import math
try:
# This operation might cause an OverflowError for very large input values
print(math.exp(1000))
except OverflowError:
print("The number is too large to be represented.")
In this example, attempting to calculate the exponential of a large number could exceed the range of floating-point numbers in Python, raising an OverflowError
. Handling this exception allows the program to continue running and manage the error gracefully.
exception RecursionError
The RecursionError is derived from the RuntimeError. This exception is raised when the interpreter detects that the maximum recursion depth is exceeded.
exception ReferenceError
The ReferenceError exception in Python is raised when a weak reference proxy, created by the weakref module, is used to access an attribute of a referent after it has been garbage collected. This occurs when attempting to access or perform operations on a resource that no longer exists. In Python, weak references enable a memory-efficient way to refer to objects without preventing their garbage collection. However, if you try to use a weakly referenced object that has been collected, Python signals this problem by raising a ReferenceError.
import weakref
class MyClass:
pass
obj = MyClass() # Create an instance of MyClass
weak_obj = weakref.ref(obj) # Create a weak reference to the object
del obj # Explicitly delete the original object
try:
print(weak_obj()) # Attempt to access the object after it's been deleted
except ReferenceError:
print("This reference is no longer valid.")
exception RuntimeError
The RuntimeError is raised when no other exception applies. It returns a string indicating what precisely went wrong.
exception StopIteration
The exception StopIteration is a built-in exception in Python that signals the end of an iterator. This exception is used to control the flow in iterator and generator functions, indicating that there are no further items to be returned. Python's loop constructs, such as for loops, automatically catch this exception and stop iterating.
my_list = [1, 2, 3]
my_iter = iter(my_list)
print(next(my_iter)) # Outputs: 1
print(next(my_iter)) # Outputs: 2
print(next(my_iter)) # Outputs: 3
try:
print(next(my_iter)) # Raises StopIteration
except StopIteration:
print("Iteration has ended.")
exception SyntaxError
The exception SyntaxError is one of the Python Built-in Exceptions. It occurs when the Python interpreter encounters a code block that does not conform to the syntax of the Python language. This error halts the execution of the program because the code is not understandable by the interpreter.
if True
print("This will cause a SyntaxError.")
In the code above, the absence of a colon (:) after the if True statement results in a SyntaxError, indicating that the syntax is incorrect. To correct the error, add a colon.
if True:
print("This is correct syntax.")
exception SystemError
The SystemError is raised when the interpreter finds an internal error. The associated value is a string indicating what went wrong.
exception SystemExit
The SystemExit is raised when sys.exit() function is called. A call to sys.exit() is translated into an exception to execute clean-up handlers (finally clauses of try statements) and to debug a script without running the risk of losing control.
exception TypeError
The exception TypeError occurs in Python when an operation or function is applied to an object of an inappropriate type. This built-in exception indicates that the data type of an object does not match the expected type for the operation or function being executed. For example, attempting to concatenate a string with an integer directly will result in a TypeError because Python does not support this operation between disparate data types.
# This will raise a TypeError
result = 'Number: ' + 123
To resolve this issue, ensure that data types are compatible for the operation. In the given example, converting the integer to a string before concatenation fixes the error:
# Correct way to concatenate string with integer
result = 'Number: ' + str(123)
exception UnboundLocalError
The exception UnboundLocalError in Python occurs when a local variable is referenced before it has been assigned a value within a function or method. This built-in exception is a subclass of the NameError and signifies issues with local scope variable access.
x = 10
def my_func():
print(x) # Attempt to reference the global variable 'x'
x = 20 # This causes UnboundLocalError
my_func()
To resolve this, you can declare the variable as global within the function or ensure it is defined before use.
when attempting to access or perform operations on a resource that no longer exists. In Python, weak references enable a memory-efficient way to refer to objects without preventing their garbage collection. However, if you try to use a weakly referenced object that has been collected, Python signals this problem by raising a ReferenceError.
import weakref
class MyClass:
pass
obj = MyClass() # Create an instance of MyClass
weak_obj = weakref.ref(obj) # Create a weak reference to the object
del obj # Explicitly delete the original object
try:
print(weak_obj()) # Attempt to access the object after it's been deleted
except ReferenceError:
print("This reference is no longer valid.")
exception RuntimeError
The RuntimeError is raised when no other exception applies. It returns a string indicating what precisely went wrong.
exception StopIteration
The exception StopIteration is a built-in exception in Python that signals the end of an iterator. This exception is used to control the flow in iterator and generator functions, indicating that there are no further items to be returned. Python's loop constructs, such as for loops, automatically catch this exception and stop iterating.
my_list = [1, 2, 3]
my_iter = iter(my_list)
print(next(my_iter)) # Outputs: 1
print(next(my_iter)) # Outputs: 2
print(next(my_iter)) # Outputs: 3
try:
print(next(my_iter)) # Raises StopIteration
except StopIteration:
print("Iteration has ended.")
exception SyntaxError
The exception SyntaxError is one of the Python Built-in Exceptions. It occurs when the Python interpreter encounters a code block that does not conform to the syntax of the Python language. This error halts the execution of the program because the code is not understandable by the interpreter.
if True
print("This will cause a SyntaxError.")
In the code above, the absence of a colon (:) after the if True
statement results in a SyntaxError, indicating that the syntax is incorrect. To correct the error, add a colon.
if True:
print("This is correct syntax.")
exception SystemError
The SystemError is raised when the interpreter finds an internal error. The associated value is a string indicating what went wrong.
exception SystemExit
The SystemExit is raised when the sys.exit() function is called. A call to sys.exit() is translated into an exception to execute clean-up handlers (finally clauses of try statements) and to debug a script without running the risk of losing control.
exception TypeError
The exception TypeError occurs in Python when an operation or function is applied to an object of an inappropriate type. This built-in exception indicates that the data type of an object does not match the expected type for the operation or function being executed. For example, attempting to concatenate a string with an integer directly will result in a TypeError because Python does not support this operation between disparate data types.
# This will raise a TypeError
result = 'Number: ' + 123
To resolve this issue, ensure that data types are compatible for the operation. In the given example, converting the integer to a string before concatenation fixes the error:
# Correct way to concatenate string with integer
result = 'Number: ' + str(123)
exception UnboundLocalError
The exception UnboundLocalError in Python occurs when a local variable is referenced before it has been assigned a value within a function or method. This built-in exception is a subclass of the NameError and signifies issues with local scope variable access.
x = 10
def my_func():
print(x) # Attempt to reference the global variable 'x'
x = 20 # This causes UnboundLocalError
my_func()
To resolve this, you can declare the variable as global within the function or ensure it is defined before use.
exception UnicodeError
This exception is a subclass of ValueError. UnicodeError is raised when a Unicode-related encoding or decoding error occurs.
exception ValueError
The exception ValueError is a built-in Python exception that indicates when a function receives an argument of correct type but improper value. It often arises when an operation or function is applied to an argument with the right type but an inappropriate value that doesn't adhere to the expected format or range.
try:
num = int("xyz")
except ValueError:
print("This is not a number.")
my_list = [1, 2, 3]
try:
position = my_list.index(4)
except ValueError:
print("Value is not in the list.")
exception ZeroDivisionError
The exception ZeroDivisionError in Python occurs when a program attempts to divide a number by zero. This is a built-in exception indicating an arithmetic error. Python treats division by zero as an illegal operation, triggering this specific error to alert the developer.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
In this code snippet, attempting to divide 10 by 0 would normally raise a ZeroDivisionError. However, the try-except block catches the exception, printing a message instead of terminating the program abruptly. This allows for graceful error handling and the continuation of program execution.