Detect division by zero: Difference between revisions

(Updated to take in account the difference between errors and defects.)
Line 2,027:
 
=={{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|Smalltalk/X}}
<lang smalltalk>zeroDividetestZeroDivide := [:aBlock |
[:aBlock |
[aBlock value. false] on: ZeroDivide do: [true].
].[
aBlock value.
false
[aBlock value. false ] on: ZeroDivide do: [true].
].
 
"Testing"
zeroDividetestZeroDivide value: [2/1] "------> false"
zeroDividetestZeroDivide value: [2/0] "------> true"</lang>
 
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}}==
Anonymous user