Day 2: Handling duplicate elements in a Binary Tree

Defining Custom Exceptions in Python🚫

As discussed in the previous post I mentioned that my implementation (or perhaps in general), the binary tree should not contain duplicate entries. Therefore I have gone the route of defining my own duplicate entry exception to be raised when a duplicate entry is attempted to be inserted into the binary tree.

Defining an Exception Class

First we define our custom exception class by extending python's Exception class

Custom Messages

We can implement custom exception messages that are displayed in the stack trace when our exception is raised. We do so by overriding the __init__() method of the Exception class. To do so, we call super.__init__(msg) inside our own __init__(self,msg) method to pass along our exception message.

The code is reflected below:  


Our exception DuplicateEntryException can now be raised when a duplicate entry is inserted into the binary tree like: 
raise DuplicateEntryException("Duplicate entries in binary tree are not allowed.")



Comments