diff --git a/creature.go b/creature.go index ae992b8..5fd8b75 100644 --- a/creature.go +++ b/creature.go @@ -29,6 +29,7 @@ const ( // registered with the same ID as another one. ErrorIDTaken Error = iota ErrorUnknownInstruction + ErrorDivideByZero ) // Error returns a textual description of the error. @@ -38,6 +39,8 @@ func (err Error) Error() (description string) { description = "this ID is taken by another function" case ErrorUnknownInstruction: description = "machine encountered unknown instruction" + case ErrorDivideByZero: + description = "cannot divide by zero" } return @@ -100,7 +103,13 @@ func (machine *Machine) Execute(offset int) (err error) { // DIV // divides the last word on the stack by the second to // last word on the stack - machine.Push(machine.Pop() / machine.Pop()) + left := machine.Pop() + right := machine.Pop() + if left == 0 && right == 0 { + err = ErrorDivideByZero + return + } + machine.Push(left / right) case 0x8: // EQ diff --git a/creature_test.go b/creature_test.go index 86572a3..617a47b 100644 --- a/creature_test.go +++ b/creature_test.go @@ -23,7 +23,12 @@ func TestArithmetic(test *testing.T) { }, } - machine.Execute(0) + err := machine.Execute(0) + if err != nil { + test.Log("machine exited with error:", err) + test.Fail() + } + addResult := machine.Pop() subResult := machine.Pop() mulResult := machine.Pop()