1.12 Exception Handling

There are two types of errors that typically occur when writing programs. The first is known as a syntax error. It means that the programmer has made a mistake in the structure of a statement or expression. The other type of error is a logic error, denotes a situation where the program executes but gives the wrong result. For example, a user enter a string rather than a number, resulting in invalid results without raising any error.

1.12.1 Syntax error

var foo = 'Tom's bar';
// Uncaught SyntaxError: Unexpected identifier

As we can see in the above code, the string is not properly escaped, leading to a runtime error that causes the program to terminate. These types of runtime errors are typically called exceptions.

Most of the time, beginners think of exceptions as fatal runtime errors that cause the end of execution. However, most programming languages provide a way to deal with these errors that will allow the programmer to have some type of intervention if they so choose. In addition, programmers can create their own exceptions if they detect a situation in the program execution that warrants it.

When an exception occurs, we say that it has been "raised". You can "handle the exception that has been raised by using a try statement. For example, consider a program that asks the user for an integer and then calculate its square root. If the user enters a negative value, the square root function will report a 'ValueError' exception.

1.12.2 Logic error

This can be due to an error in the underlying algorithm or an error in your translation of that algorithm.

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('Enter an integer?', (num) => {

  var squareRoot = Math.sqrt(num);
  console.log('The square root of', num, 'is', squareRoot);

  rl.close();
});

In the case of the above code, if you enter a string or a negative number, the result will be NaNor Not a Number but no exception will occur.

results matching ""

    No results matching ""