Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

CHAPTER 10 : JAVASCRIPT ERROR TRAPPING

OBJECTIVES:
➢ Learn why error detection and trapping are needed
➢ Learn the causes of errors
➢ Learn how to detect and handle errors

Why Do You Need to Detect Errors?

Errors are flaws that are developed on the course of the program development or deployment. Errors need
to be handled properly so that the program will not crash; That is, prepare the program so it will know what
to do when it faces a certain error.

Causes of Errors

There are times when an error occurs during the development of the program. It could be a logical, a run-
time or a syntax error. When we say logical errors, it means that there is something wrong with the logic or
the flow of the program. It could be because of wrong mathematical expression or the wrong variable was
used for a computation. Run-time error happens when an error has occurred during run time. It could be
because of memory leak. Syntax error happens when the program has encountered a miswritten syntax of
a program. It could be because of wrong capitalization or keywords, lack of quotation marks, etc.

How to Handle Errors

In JavaScript, we use the try-catch block to do error trapping.

Syntax of a try-catch try

// put your main codes here

catch (err)

// put your solutions here if an error occurs

}
The try block will test a block of code for errors. When an error occurs, the catch
block will be executed. The throw statement can be used to make error trapping
more accurate and precise.

Video Links:
https://www.youtube.com/watch?v=79RjHaAYT-4

References:
https://www.w3schools.com/js/js_errors.asp
https://www.w3schools.com/jsref/event_onerror.asp
https://www.w3schools.com/jsref/jsref_throw.asp

You might also like