try-catch …. Always the confusion — JavaScript?

lalala;     
// Error msg:ReferenceError: lalala is not defined - code dies here
// my next codes.
console.log('initiating a service'); // this code will break
try {lalala;} catch(err) {console.log(err.stack);   // this will throw in console}console.log('next codes'); // this code will execute
  1. use try-catch wherever you feel javaScript engine will throw error.
  2. it will prevent code break
  1. First, the code in try {...} is executed.
  2. If there were no errors, then catch(err) is ignored: the execution reaches the end of try and goes on, skipping catch.
  3. If an error occurs, then the try execution is stopped, and control flows to the beginning of catch(err). The err variable (we can use any name for it) will contain an error object with details about what happened.
try {   
lalala; // error, variable is not defined!
} catch(err) {
alert(err.name); // ReferenceError
alert(err.message); // lalala is not defined
alert(err.stack); // ReferenceError: lalala is not defined at
// (...call stack) // Can also show an
// error as a whole // The error is
// converted to string as "name: message"
alert(err); // ReferenceError: lalala is not defined
}
// Valid JSON
let task = '{"companyNameAr":"جريبي","eadLicenseNumber":"CF-359","externalEntityLicenseNumber":"IN-2003833","companyName":"IN-2003833 TEST","licenseIssuanceEntityId":1,"profileCompanyNameAr":"","eqsApplicationId":5399,"profileCompanyId":null,"profileCompanyName":""}';
let user = JSON.parse(task);console.log(user);
try {    let task = '{bad request}';    let user = JSON.parse(task);} catch(err) {    console.log('Error Object: ', err); // error prints as invalid json}// next codes will work
let json = '{ "age": 30 }'; // incomplete datatry { let user = JSON.parse(json); if(!user.name) {    throw new SyntaxError('Error: incomplete user data');    alert(user.name); }} catch(e) {console.log(e.message); // O/P - Error: incomplete user data}
  1. Catch gets all errors.
  2. In the catch(err) {...} block we analyze the error object err.
  3. If we don’t know how to handle it, we do throw err.
function readData() {    let json = '{ "age": 30 }';    try {        // ...        blabla(); // error!    } catch (e) {     // ...     if (!(e instanceof SyntaxError)) {         throw e; // rethrow (don't know how to deal with it)     }   }}try {    readData();} catch (e) {    alert( "External catch got: " + e ); // caught it!}
  • after try, if there were no errors,
  • after catch, if there were errors.
try {
... try to execute the code ...
} catch(e) {
... handle errors ...
} finally {
... execute always ...
}
<script>   // Handeling global error
window.onerror = function(message, url, line, col, error) {
alert(`${message}\n At ${line}:${col} of ${url}`);
};
function readData() {
badFunc(); // Whoops, something went wrong!
}
readData(); </script>
try {
// run this code
} catch(err) {
// if an error happened, then jump here
// err is the error object
} finally {
// do in any case after try/catch
}
  • message – the human-readable error message.
  • name – the string with error name (error constructor name).
  • stack (non-standard, but well-supported) – the stack at the moment of error creation.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amir Mustafa

Amir Mustafa

JavaScript Specialist | Consultant | YouTuber 🎬. | AWS ☁️ | Docker 🐳 | Digital Nomad | Human. Connect with me on https://www.linkedin.com/in/amirmustafa1/