Custom Exceptions
In Python, you can create custom exceptions to handle specific error scenarios. This allows you to create more meaningful and descriptive error messages for your programs.
Task
Build a program that calculates the area of various shapes. Use custom exceptions to handle different types of shape calculation errors.
JavaScript implementation
classInvalidShapeExceptionextendsError{
constructor(message){
super(message);
this.name="InvalidShapeException";
}
}
classNegativeDimensionExceptionextendsError{
constructor(message){
super(message);
this.name="NegativeDimensionException";
}
}
functioncalculateRectangleArea(length, width){
if(typeof length !=="number"||typeof width !=="number"){
thrownewInvalidShapeException("Invalid dimensions. Length and width must be numbers.");
}
if(length <=0|| width <=0){
thrownewNegativeDimensionException("Invalid dimensions. Length and width must be positive numbers.");
}
return length * width;
}
console.log(calculateRectangleArea(5,4));// Output: 20
console.log(calculateRectangleArea("5",4));// Throws InvalidShapeException
console.log(calculateRectangleArea(-5,4));// Throws NegativeDimensionException
Python implementation
# Define custom exceptions
classInvalidShapeException(Exception):
def__init__(self, message):
super().__init__(message)
classNegativeDimensionException(Exception):
def__init__(self, message):
super().__init__(message)
defcalculate_rectangle_area(length, width):
ifnotisinstance(length,(int,float))ornotisinstance(width,(int,float)):
raise InvalidShapeException("Invalid dimensions. Length and width must be numbers.")
if length <=0or width <=0:
raise NegativeDimensionException("Invalid dimensions. Length and width must be positive numbers.")
return length * width
print(calculate_rectangle_area(5,4))# Output: 20
print(calculate_rectangle_area("5",4))# Raises InvalidShapeException
print(calculate_rectangle_area(-5,4))# Raises NegativeDimensionException
Code Highlight
- The base class for exceptions in Python is
Exception
, while in JavaScript it isError
. Both languages useclass
to inherit from the base class and create custom exceptions. - Python uses the
isinstance()
function to check the type of a variable, while JavaScript usestypeof
andinstanceof
.
Common API
Feature | JavaScript | Python |
---|---|---|
Creating custom exception | class CustomException extends Error {} | class CustomException(Exception): |
Throwing custom exception | throw new CustomException(message) | raise CustomException(message) |