JavaScript Tutorial Series – Exceptions

In JavaScript, errors can be caught using exception handling. Exception handling will prevent an application from crashing and not being able to recover. Exception handling is a much cleaner way than the old fashioned way of setting up your own error codes, passing them around and doing comparisons.
Exception handling is implemented using try catch blocks. The try statement encloses a block of code to run. The catch captures runtime errors that occurred within the code block. Captures contain code to handle what to do when errors occur. Finally blocks are optional and contain a block of code that always runs after the try/catch, whether or not an error occurred. Throw statements are custom errors sent from a block of code to the block of code that called it. The first try/catch encountered in the calling chain will handle the error.
The throw statement can throw a string, number, boolean or object.
The throw statement can be used as follows:

 function addNumbers(a, b) { if (typeof a != 'number') { throw 'Not a number'; } if (typeof b != 'number') { throw 'Not a number'; } return a + b; } try { let sum = addNumbers(7, 'abc'); console.log('sum: ' + sum); } catch (error) { console.log('Error: ' + error.message); }

The error variable in the catch statement is an object with name and message properties.

Implementation:

Inside the modules/Weather.js file created in the JavaScript objects tutorial, add the following lines that are in bold:

 class Weather { // Constructor constructor() { }; getLocation() { let url = 'https://ipinfo.io/json'; let options = { mode : 'cors' }; fetch(url, options) .then(response => response.json()); };  static convertKelvinToCelsius(kelvin) { if (typeof kelvin !== 'number') { throw 'Kelvin value is not a number'; } return Math.round(kelvin - 273); } static convertCelsiusToFahrenheit(celsius) { if (typeof celsius !== 'number') { throw 'Celsius value is not a number'; } return Math.round((celsius * (9/5)) + 32); }; static convertFahrenheitToKelvin(fahrenheit) { if (typeof fahrenheit !== 'number') { throw 'Fahrenheit value is not a number'; } return Math.round(((5/9) * (fahrenheit - 32)) + 273); }; }  export default Weather;

This adds 3 functions that verify the input parameter is a number before performing the conversion calculations. If the value is not a number, an exception is thrown using the throw statement.

Next, inside the javascript_tutorial.js file created in the JavaScript set up tutorial, add the following lines that are in bold:

 // JavaScript Tutorial /* * This file will add JavaScript * to a website. */  import Weather from "./modules/Weather.js"; (function() { let doc = document; let defaultLocation = [-86.7816, 36.1627]; // longitude, latitude  function setWeather(data) { if (data) { let temp = Math.round(data.main.temp); try { let fahrenheit = Weather.convertCelsiusToFahrenheit(temp - 273); console.log("Fahrenheit temperature: " + fahrenheit); } catch (error) { console.log("Error setting weather: " + error.message); } } } function init() { let locationStr = ""; for (let i = 0, num = defaultLocation.length; i < num; i++) { locationStr += defaultLocation[i]; if (i === 0) { locationStr += ", "; } } console.log("Setting weather for location: " + locationStr);  setWeather({ main: { temp: 30 } }); } init(); })();

The new lines create a function called setWeather that converts the input value to fahrenheight. Exception handling is added in case the conversion function throws an error.

In the index.html file, edit the script included at the bottom of the file to read:

 <script src="js/javascript_tutorial.js" type="module"></script>

This will allow the javascript_tutorial.js file to import the Weather class. Modules will be explained in a future post.

The JavaScript tutorial series starts with this post.

(paid links)

More JavaScript