What is an exception?
In short
An exception is an error that happens while a program is running, like dividing by zero or opening a file that isn't there. You can catch it and handle it instead of crashing.
Some problems can't be spotted until the program runs: the user types "twelve" instead of 12, or the internet drops. When that happens the language raises an exception, and if nothing handles it, the program stops.
Wrapping risky code in try and except (or try and catch in JavaScript) lets you deal with the problem calmly, for example by asking the user to try again.
Python
Handle text that isn't a number
text = "twelve"
try:
number = int(text)
print(number * 2)
except ValueError:
print("Please type a number")Output
Please type a numberJavaScript
The same idea in JavaScript
try {
JSON.parse("{not json}");
} catch (error) {
console.log("That isn't valid JSON");
}Output
That isn't valid JSONLearn it properly
These free lessons teach it step by step, with questions and a program you write yourself.
Try your first lesson free
Codiqo teaches coding in five-minute lessons with real code. Free on the web, iPhone and Android.