Exceptions
In JavaScript, exceptions are a way of handling unexpected errors or exceptional situations that may occur during the execution of a program. When an error occurs, an exception object is created, and the normal flow of the program is disrupted.
To handle exceptions, JavaScript provides a mechanism known as try...catch
.
try...catch
The try...catch
statement is comprised of a try block and either a catch block, a finally block, or both.
try {
// Code that might throw an exception
let result = abc / 0; // This will throw a error
console.log(result); // This line will not be executed
} catch (error) {
console.log(`An error occurred: ${error.message}`);
// An error occurred: abc is not defined
} finally {
console.log('This will be executed regardless of whether an exception occurred or not.');
}
Code Challenge
Write a function
safeDivision
that takes two parameters (numerator
anddenominator
) and returns the result of dividing the numerator by the denominator. However, if thedenominator
is zero, catch the exception and return a custom error message.
Loading...
> code result goes here