Types of errors in programming
In programming, errors can be any of the following types:
1. Syntax error
2. Runtime error
3. Logical error
Let’s talk about them one by one
If you don’t know what does syntax means, let me provide a definition to you
Syntax is the arrangement of words and phrases to create well-formed sentences in a language
So, every language have some predefined ways to write a program and when you make some mistake putting words or literals at wrong place and even missing them sometimes, can result into Syntax error.These errors are also refered as Parsing errors
In below example, we have missed the closing parenthesis while using
var str="Hello World";
The below code will result into a runtime error at line
var result = x.getString();
Uncaught TypeError: x.getString is not a function
throw (we are going to see later in this article) to let the user know about the error.
finally statements. Whenever an error occurs the technical term we use for it is throwing an exception .
This allows you to test for errors in your code.You put the code you want to test within
This block actually let’s you handle the errors thrown. The error object
err has all the details about the errors.
Your code inside the
finally block always gets executed after try and catch .It doesn’t depend on whether the code ran successfully or with some error.
Now, let’s understand them with an example
Something went wrong TypeError: str.getNumber is not a function at window.onload ((index):35) This should always get executed
Sometimes you need to create custom errors and throw them when needed, may be when there is some logical error and you want the user to know something wrong happened.
Let’s see an example of an logical error and how we can use
throw to throw an exception. In this example we are going to iterate an array and log each of it’s elements. At the end we are going to count the number of elements that are not printed(if any) and throw an exception with the count of not printed elements.
The number , 2 The number , 3 The number , 4 The number , 5 Uncaught 1 element(s) is/are not printed
This function fires the error event on
window object whenever there is an error during runtime.Generally this is used with the syntax
Some error occured Uncaught ReferenceError: someFunction is not defined
Another usage of
onerror() is to handle error while loading an image just list the below example.
Happy Coding !!!