Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to catch NotImplementedError Exception in Python?
The NotImplementedError exception in Python is raised when an abstract method or operation that should be implemented by a subclass is not implemented. It is commonly used as a placeholder in base classes to indicate that subclasses are expected to override the method.
In this article, you will learn how to catch and handle the NotImplementedError in Python using simple examples.
When Does NotImplementedError Occur?
The NotImplementedError is usually raised in the following cases −
- A method is defined in a base class but is not implemented and used as a placeholder for child classes to override.
- The subclass does not provide an implementation for the method and calls the base method, causing the exception.
Catching NotImplementedError with try-except
Example: Basic Exception Handling
In the following example, the base class defines a method that raises NotImplementedError. If the subclass does not override it, the error will be raised at runtime −
class Animal:
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
pass
try:
d = Dog()
d.speak()
except NotImplementedError as e:
print("Caught NotImplementedError:", e)
Following is the output obtained −
Caught NotImplementedError: Subclasses must implement this method
In this example, the Dog class does not override the speak() method, so the call to d.speak() raises a NotImplementedError, which is caught and handled.
Example: Proper Implementation to Avoid Exception
If the subclass properly implements the method, the exception does not occur −
class Animal:
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Cat(Animal):
def speak(self):
print("Meow!")
try:
c = Cat()
c.speak()
except NotImplementedError as e:
print("Caught NotImplementedError:", e)
We get the output as shown below −
Meow!
Here, the Cat class overrides the speak() method, so the NotImplementedError is not raised.
Handling Multiple Methods
Example: Multiple Abstract Methods
You can handle multiple methods that might raise NotImplementedError −
class Vehicle:
def start(self):
raise NotImplementedError("Subclasses must implement start()")
def stop(self):
raise NotImplementedError("Subclasses must implement stop()")
class IncompleteVehicle(Vehicle):
def start(self):
print("Vehicle started")
try:
vehicle = IncompleteVehicle()
vehicle.start()
vehicle.stop() # This will raise NotImplementedError
except NotImplementedError as e:
print("Missing implementation:", e)
The output of the above code is −
Vehicle started Missing implementation: Subclasses must implement stop()
Using abc Module for Better Abstract Classes
Example: Abstract Base Classes
Python's abc module provides better support for abstract methods −
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
try:
rect = Rectangle(5, 3)
print("Area:", rect.area())
except NotImplementedError as e:
print("Caught NotImplementedError:", e)
Following is the output obtained −
Area: 15
Conclusion
Use try-except blocks to catch NotImplementedError when working with abstract methods. Consider using Python's abc module for better abstract class design and error prevention at instantiation time.
