自定义异常
在 Python 中,可以自定义异常来处理特定的错误场景,这样可以为程序创建更有意义和描述性的错误消息。
任务
构建一个计算各种形状的面积的程序。使用自定义异常来处理不同类型的形状计算错误。
JavaScript 实现
class InvalidShapeException extends Error {
constructor(message) {
super(message);
this.name = "InvalidShapeException";
}
}
class NegativeDimensionException extends Error {
constructor(message) {
super(message);
this.name = "NegativeDimensionException";
}
}
function calculateRectangleArea(length, width) {
if (typeof length !== "number" || typeof width !== "number") {
throw new InvalidShapeException("无效的尺寸。长度和宽度必须是数字。");
}
if (length <= 0 || width <= 0) {
throw new NegativeDimensionException("无效的尺寸。长度和宽度必须是正数。");
}
return length * width;
}
console.log(calculateRectangleArea(5, 4)); // 输出: 20
console.log(calculateRectangleArea("5", 4)); // 抛出InvalidShapeException
console.log(calculateRectangleArea(-5, 4)); // 抛出NegativeDimensionException