Core programming fundamentals · Lesson 14 of 60 · Code lesson, JavaScript or Python · Optional
Error handling
An error happens when something goes wrong while a program runs, such as turning the text "abc" into a number.
Validation checks input before it is used, and error handling lets a program recover instead of crashing.
A friendly message that says what to fix is better than a crash.
Worked example
In JavaScript, Number("abc") does not crash; it gives NaN (not a number), which this practice runner shows as null, so check with Number.isNaN. Code that can throw is wrapped in try and catch.
const text = "abc";
const number = Number(text);
if (Number.isNaN(number)) {
console.log("Not a number");
} else {
console.log(number * 2);
}Output: Not a number
In Python, int("abc") raises a ValueError. try runs the risky code, and except catches the error so the program can recover.
text = "abc"
try:
number = int(text)
print(number * 2)
except ValueError:
print("Not a number")Output: Not a number
Your turn
Right now bad input breaks the program. Make it print "Please enter a number" when the input is not a number, and print double the number otherwise.
Your program is checked with these 3 inputs:
Input:
21
Expected output:
42
Input:
abc
Expected output:
Please enter a number
Input:
0
Expected output:
0
Loading your practice…
Preparing your workspace…