Skip to content

Instantly share code, notes, and snippets.

function foo(x) {
if (typeof x !== 'number') {
throw new TypeError('x is not a number');
}
return new Promise((resolve, reject) => {
resolve(x);
});
}
async function run() {
try {
await foo();
} catch(err) {
// This block will be reached now.
} finally {
// This block will be reached at the end.
}
}
run();
try {
foo();
} catch(err) {
// This block won’t be reached.
} finally {
// This block will be reached before the Promise is rejected.
}
try {
foo();
} catch(err) {
// This block won’t be reached.
} finally {
// This block will be reached before the Promise is rejected.
}
return Promise.Reject(new Error())
async function foo() {
throw new Error();
}
function foo2() {
try {
throw new Error();
} catch {
return true;
} finally {
return false;
}
}
function foo1() {
try {
return true;
} finally {
return false;
}
}
try {
If (typeof x !== ‘number’) {
throw new TypeError(‘x is not a number’);
} else if (x <= 0) {
throw new RangeError(‘x should be greater than 0’);
} else {
// Do something useful
}
} catch (err) {
if (err instanceof TypeError) {
try {
// a function that potentially throws an error
someFunction();
} catch (err) {
// this code handles exceptions
console.log(e.message);
} finally {
// this code will always be executed
console.log(finally’);
}