try and catch
JavaScript · Unit 9: Errors and exceptions
- Full plan
- JavaScript
- 10 exercises
try attempts to run a block. If something crashes inside, instead of stopping the program, JavaScript jumps to the catch block, and then carries on with what comes below.
Whatever was left in the try after the error doesn't run.
try {
console.log("Before");
console.log(totl);
console.log("Never here");
} catch (error) {
console.log("Something failed");
}
console.log("Still here");Prints
Before Something failed Still here
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Complete the code
Complete it so the program doesn't crash if the person has no address.
4. Predict the output
What does this code print?
5. Complete the code
Complete it to print only the error's message, the part that explains what failed.
6. Predict the output
Now the whole error gets printed. What comes out?
7. Find the bug
If the object has no name, the function should return "NO NAME", but here
undefinedgets printed. Which line has the error?8. Put the lines in order
Order the function that returns the first letter of the name, or "?" if the object has no name.
9. Find the case that fails
greet(p)should return "Hi, " with the name without extra spaces, or "Hi, friend" if the object has no name. Which call does it fail with?10. Predict the output
The
tryis inside the loop. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.