prøv, fang, kast: when something goes wrong
Error handling in Norscode is a clear part of the flow, not something you discover when it blows up.
No code meets only the perfect day. The file does not exist, the network does not answer, the user typed something strange. The question is not whether something goes wrong, but whether your code has decided what should happen when it does.
Three words
Norscode uses prøv, fang and kast. You prøv something that can fail; if it goes wrong, you fang the error and decide what happens; and you can yourself kast an error when it makes no sense to continue. The words are Norwegian, and the flow reads like a sentence.
Errors that are visible
In many languages it is easy to let an error slip by quietly, until it shows up somewhere else entirely much later. When the error handling is a clear block in the code, whoever reads it sees that "here something can go wrong, and here is what we do". That makes the program easier to understand, and easier to trust.
Not everything should be caught
A good rule is to only catch what you can actually do something about. If you cannot fix it, it is often better to let the error bubble up to someone who can — than to hide it behind an empty block. Norscode makes both easy, but makes it visible what you chose.
Error handling is not the fun thing to write. But it is often the difference between a program that endures a bad day, and one that does not.
A small example
Say you are going to read a file that may not exist. Instead of letting the program crash, you wrap the attempt:
prøv {
la innhold = fil.les("data.txt")
skriv(innhold)
} fang (e) {
skriv("Kunne ikke lese fila")
}The prøv block runs, and if something goes wrong, execution jumps straight to fang, where you decide what should happen. The program continues instead of stopping abruptly, and whoever reads the code sees clearly where it can go wrong and what the answer is.
kast when something makes no sense
Sometimes the right thing is to stop. If your function discovers a state it cannot continue from, it can itself kast an error, which a block further out can catch. That way you let errors bubble upward to the place that actually knows what should be done, instead of guessing locally.
A good rule
Catch only what you can do something about. If you cannot fix it, it is often better to let the error move on than to hide it behind an empty block where it disappears without a trace. Norscode makes both easy — but makes it visible in the code what you chose, so the next reader does not have to guess.
Related
- Norscode or Python?An honest comparison of two accessible languages — one where Python also comes out well.
- Norscode or Go?Two languages that value simplicity and a single deployable unit — but choose differently on syntax and security.
- Norscode or JavaScript?JavaScript is everywhere. In some areas a young language cannot compete — in others, that is exactly the point.