Skip to content
When it goes wrong

When it goes wrong

Things go wrong at two moments: while the compiler reads your program, and while the program runs. qdx tries to move as much as it can to the first.

A mistake the compiler finds

Put this in wrong.qdx.

fn main() -> int {
  1 + true
}
bootstrap/qdx wrong.qdx -o wrong
wrong.qdx:2:7: error: right operand must be int but is bool

Every error has the same shape: the file, the line, the column, and a sentence saying what was expected and what was there. The compiler stops at the first one, writes no executable, and exits with status 1.

A missing match arm reads the same way.

union light { red(), green(), blue() }

fn code(l: light) -> int {
  match l {
    red() => 1,
    green() => 2
  }
}

fn main() -> int { code(red()) }
light.qdx:4:3: error: match on 'light' is missing: blue

Stopping on purpose

Some problems only show up when the program meets real data. A line on Mira’s score sheet might have a name and no points. There is no sensible value to produce for that, so the program should say what is wrong and stop.

panic does that. It writes a message to standard error and ends the program with status 1.

fn points_or_stop(points: int) -> int {
  if points < 0 { panic("points cannot be negative") } else { points }
}

fn main() -> int { points_or_stop(0 - 3) }
points cannot be negative

One branch of that if produces an int and the other calls panic, yet the two are accepted as the same type. panic is declared to return never, the type of something that does not come back, and never is allowed wherever any other type is expected.

A mistake only running finds

Dividing by zero cannot be seen in advance, so it is caught when it happens.

fn average(sum: int, rounds: int) -> int { sum / rounds }

fn main() -> int { average(17, 0) }
bootstrap/qdx std/*.qdx average.qdx -o average
./average
average.qdx:1:48: error: division by zero

The message points at the division in your source, in the same shape as a compiler error, and the program exits with status 1.

With errors understood, the score program can meet real data. The next chapter reads the sheet from a file.