Skip to content

Re: your question on error handling in _init_ functions #1

@karl-project-review

Description

@karl-project-review

Note: Hello, there is something i would like to fix.
When I have a constructor error, I don't really know how to handle it. I saw that __del__ with the variable you have created would fix it,
but I haven't seen that function in this course, so I have decided to equal the inner variables to my own error values.
'''
#User object
class User(object):
def __init__(self, name, email):
if type(name) == str and type(email) == str and '@' in email and ('.com' in email or '.edu' in email or '.org' in email):
self.name = name #string
self.email = email #string
self.books = {} #dictionary
else:
print("User's constructor error")
self.name = "Error" #string
self.email = "Error" #string
self.books = {} #dictionary

I would recommend doing these checks in the TomeRater class' add_user function (it looks like you already do checks in the create_book, create_novel, and create_nonfiction functions, which is great). Since the system is designed such that end users should be accessing the User, Books, etc classes all through the TomeRater class, we can handle improper input in TomeRater's class functions, and then just let these other classes throw exceptions if their init functions fail for some other reason (and handle these exceptions using try-except blocks in TomeRater). Creating instances of classes that are designated as failures like is done here could pollute and clog up an active program, so ideally we should (1) not call init for classes until the input has already been validated and (2) let any other improper calls to init fail, as then Python's automatic garbage collection will deal with any necessary memory-freeing that needs to be done.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions