我正在设计我自己的 OO 语言,并且一直很开心,直到遇到异常。在我看来,异常打破了封装。
例如,如果 A 类有 B 类的对象,B 有 C,C 有 X,这会向 A 抛出异常,那么 A 中的代码不仅要知道 X,还要知道 B 和 C 才能正确处理。您可以这样说,因为如果您将 C 替换为 D,则必须更改异常的处理程序以从调用堆栈中提取相关信息。
我能想到的解决此问题的唯一方法是将异常作为类 API 的一部分,以便它们一次向调用堆栈传播一个调用者。他们应该以自己的方式重新中断异常。
这是一个例子。Trend 是一个用于分析统计趋势的类,它有一种方法,斜率,用于从两点计算直线的斜率。
method slope
given
Point 1st
Point 2nd
returns
Number m
except
when infinite slope
m gets
( 2nd's y - 1st's y ) / ( 2nd's x - 1st's x )
except
when any divide by zero
declare infinite slope
when overflow of ( 2nd's y - 1st's y )
declare infinite slope
when overflow of ( 2nd's x - 1st's x )
instead do m gets 0
when overflow of ( 2nd's y - 1st's y ) / ( 2nd's x - 1st's x )
declare infinite slope
when any underflow
instead use 0
end of method slope
有一个更好的方法吗?