Compile errors vs runtime exceptions
Scala programs fail in two very different ways. A compile error stops the program before it starts: the compiler has proved something is wrong, points at the exact line and column, and nothing runs. A runtime exception happens while the program is running: the code was valid, but some value — an empty list, a null from Java, bad input — made an operation impossible, and the JVM prints a stack trace. Scala's type system is designed to move as many bugs as possible from the second group into the first.
Compile error
- Printed by the compiler, starts with
-- [E007] Type Mismatch Error:or similar - Ends with
1 error found/Compilation failed - Nothing ran — no output at all
- Points at a file, line and column, with a caret under the problem
- Fix it and it is gone for good
Runtime exception
- Printed by the JVM, starts with
Exception in thread "main" - Followed by a stack trace: lines starting with
at - Earlier output already printed; the crash happened part way through
- Depends on the data: the same code may work on other input
- Fix the cause, then make the bad case a value (
Option,Either)
Anatomy of a Scala 3 compiler message
-- [E007] Type Mismatch Error: Main.scala:2:17
2 | val age: Int = "42"
| ^^^^
| Found: ("42" : String)
| Required: Int
|
| longer explanation available when compiling with `-explain`
1 error found
Compilation failedThe exact output of compiling a two-line program that assigns a String to an Int.
| Part | Meaning |
|---|---|
[E007] | The error code. Search "Scala 3 E007" to find the documented explanation. |
Type Mismatch Error | The category: type mismatch, not found, syntax, cyclic, type error... |
Main.scala:2:17 | File, line 2, column 17. Editors turn this into a clickable link. |
The code line and ^^^^ | The exact expression the compiler objects to. |
Found / Required | What you gave versus what that position needs. ("42" : String) means "the literal "42", of type String". |
-explain hint | Recompile with that flag for a long explanation of this error. |
scala compile -explain Main.scala
# in sbt, add to build.sbt: scalacOptions += "-explain"Ask the compiler to explain every error in detail.
