Consider this JavaScript code that throws a string as an error. What will be printed to the console?
try { throw "Oops! Something went wrong."; } catch (e) { console.log(e); }
When you throw a string, the catch block receives that string directly.
Throwing a string means the catch block gets that string as the error value. So logging it prints the string itself.
What error will be thrown by this code snippet?
function test() { throw new TypeError('Wrong type!'); } try { test(); } catch (e) { console.log(e.name); }
Look at the type of error created with new.
The code throws a TypeError object, so e.name is "TypeError".
What will be the output of this code?
try { throw {code: 404}; } catch (e) { console.log(e.message); }
The thrown object does not have a message property.
Since the thrown object only has a code property and no message, e.message is undefined.
What will this code print?
class CustomError extends Error { constructor(msg) { super(msg); this.name = 'CustomError'; } } try { throw new CustomError('Custom problem'); } catch (e) { console.log(e.name + ': ' + e.message); }
The custom error sets its name property explicitly.
The error's name is "CustomError" and message is "Custom problem", so the output combines both.
What will this code print to the console?
new Promise((resolve, reject) => { throw new Error('Promise failed'); }).catch(e => { console.log(e.message); });
Throwing inside a Promise executor triggers the rejection.
Throwing an error inside the Promise executor causes the Promise to reject with that error, so the catch handler receives it and logs its message.