AttributeError
can be defined as an error raised when an attribute reference or assignment fails.
This code tries to append to a string object.
The code first creates a string object str
with the value “Test”. Then, it calls the append
method on this string object, which is not valid as strings are immutable in Python, and cannot be modified. This operation would result in an AttributeError
.
To handle such exceptions, the code uses a try-except
block to catch the error. In case an AttributeError
is raised, the code inside the except
block will be executed.
The code inside the except
block first prints the message “AttributeError occurred:” and then prints the error message contained in the exception object e
using print(e)
.
The try-except
block allows the code to continue executing even in the presence of errors, without crashing the program. It provides a way to handle exceptions and provides a more user-friendly output.
try:
str = "Test"
str.append()
except AttributeError as e:
print("AttributeError occurred: ")
print(e)
AttributeError occurred:
'str' object has no attribute 'append'
This code defines a Person
class with an __init__
method that initializes two attributes prename
and name
to “John” and “White” respectively.
The code then creates an instance of the Person
class, and tries to access and print the values of the prename
and name
attributes. It then tries to access the value of an undefined attribute age
on the Person
instance p
.
Since the attribute age
is not defined for the Person
class, accessing it would result in an AttributeError
.
To handle such exceptions, the code uses a try-except
block to catch the error. In case an AttributeError
is raised, the code inside the except
block will be executed.
The code inside the except
block first prints the message “AttributeError occurred:” and then prints the error message contained in the exception object e
using print(e)
.
The try-except
block allows the code to continue executing even in the presence of errors, without crashing the program. It provides a way to handle exceptions and provides a more user-friendly output.
class Person:
def __init__(self):
self.prename = "John"
self.name = "White"
try:
p = Person()
print(p.prename + " " + p.name)
print(p.age)
except AttributeError as e:
print("AttributeError occurred: ")
print(e)
AttributeError occurred:
'Person' object has no attribute 'age'