Skip to main content

Try-Catch

Sometimes, code fails.

The try...catch blocks help with code failing. Step 1 shows up fine, the function call to a nonexistent function fails it out and it never gets to step 3. image.png

Fix:

console.log("Step 1");
try {
nonExistentFunction();
} catch (error) {
console.error(`The error be: ${error}`); // Uncaught ReferenceError: nonExistentFunction is not defined
}
console.log("Step 2");

You can do whatever you'd like in the catch block. Maybe if you're trying to access X, and the API is down, you might want to return an error message to the user that X is not available.

Example #2


const runCode = () => {
console.log("Step 1");
try{
getData();
} catch{
console.log("things broked")
}
console.log("Step 2");
}

// Sample usage - do not modify
runCode();

Get Date Failure


We've provided you with a function getDate() that returns a string representing the current date (for example, 22/3/2021). However, this function fails 50% of the time (in an attempt to simulate the concept of functions that might fail sometimes).

When it fails, the function showDate() also breaks because it's calling getDate(). Update the implementation of showDate() such that it returns the date (when possible), otherwise the string "Could not get date".

import {getDate} from "./helpers.js";

const showDate = () => {
try {
const date = getDate();
return date;
} catch {
return "Could not get date"
}
}

// Sample usage - do not modify
console.log(showDate());