Detect division by zero: Difference between revisions
Content added Content deleted
(Updated to take in account the difference between errors and defects.) |
|||
Line 2,027: | Line 2,027: | ||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
{{works with|Smalltalk/X}} |
|||
<lang smalltalk>|didDivideByZero a b| |
|||
didDivideByZero := false. |
|||
a := 10. |
|||
b := 0. |
|||
[ |
|||
a/b |
|||
] on: ZeroDivide do:[:ex | |
|||
'you tried to divide %P by zero\n' printf:{ex suspendedContext receiver}. |
|||
didDivideByZero := true. |
|||
]. |
|||
didDivideByZero ifTrue:[ |
|||
Transcript show:'bad bad bad, but I already told you in the handler'. |
|||
].</lang> |
|||
Alternative version, which gets any block as argument, evaluates it and returns true, if ZeroDivide happened (works in all Smalltalks): |
|||
{{works with|Squeak}} |
{{works with|Squeak}} |
||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
<lang smalltalk> |
<lang smalltalk>testZeroDivide := |
||
[:aBlock | |
|||
⚫ | |||
[ |
|||
aBlock value. |
|||
false |
|||
⚫ | |||
]. |
|||
"Testing" |
"Testing" |
||
testZeroDivide value: [2/1] "------> false" |
|||
testZeroDivide value: [2/0] "------> true"</lang> |
|||
of course, as ZeroDivide inherits from Error, you could also write [...] on: |
of course, as ZeroDivide inherits from Error, you could also write <land smalltalk>[...] on:Error do: [...]</lang>, thereby catching ANY error (as done in some other code examples here). |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |