Added a division by zero error

This commit is contained in:
Sasha Koshka 2022-08-28 18:20:09 -04:00
parent dabd2df07c
commit b4bd86ad1d
2 changed files with 16 additions and 2 deletions

View File

@ -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

View File

@ -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()