Exception types in javascript

The Basics of Exception Handling in JavaScript

With the use of exceptions, you can responsibly manage some of these problems we face as developers. Exception handling is the process of converting a code error message into a user-friendly error message. It is a necessary step in the development process.

In this article, we will go through exception handling in JavaScript.

Table of Contents

Prerequisites

Exception handling in JavaScript is an exciting and interactive topic. Therefore, I recommend the reader have a basic understanding of HTML, CSS, and JavaScript.

What is exception handling

Exception handling is one of the powerful JavaScript features to handle errors and maintain a regular JavaScript code/program flow.

An exception is an object with an explanation of what went amiss. Also, it discovers where the problem occurred. Errors occur due to mistakes made by developers, wrong input, or unforeseeable things.

A few reasons why exceptions occur are listed below:

  • Dividing a number by zero: This results in infinity, thus throwing an exception.
  • When a requested file does not exist in the system.
  • When the user provides the wrong input.
  • When the network drops during communication.

If a software engineer fails to plan for failure, then whatever project or code they are working on may not be successful (when an error does occur). That is where exception handling comes into play.

Читайте также:  Js прочитать файл css

When JavaScript encounters an error and raises an exception. The JavaScript translator looks for an exception handling code rather than proceeding to the next statement. In a programming environment, exceptions can be handled, but errors cannot.

JavaScript error types

Different errors may occur while executing a JavaScript code. There are three types of errors.

  1. Syntax Errors: These are errors that cannot be interpreted by the computer. These errors stop the program from working.

In JavaScript, these errors are:

  • Spelling errors (wrong spelling such as fiction instead of function).
  • The omission of important characters, such as not using a semicolon to end a statement.
  • Use of the wrong indentation.
  1. Runtime Errors: These errors take place during execution. The errors get detected when your program runs. It crashes or raises an exception. Thus, exception handlers handle exception errors.

These errors are often caused by:

  • The program not being able to find data because it does not exist.
  • The data being an invalid type of data.
  1. Logical Errors: These types of errors do not throw an error or an exception at all. This is because they result from the code not doing what the developer intends it to. It’s challenging to find logical errors. They can only be found through thorough testing.

Error objects

When a runtime error occurs, it stops the code and raises an error object.

The error object has two properties:

  • Name: It gives the error name.
  • Message: It sets or returns the error message in the form of a string.

JavaScript uses six types of error objects. These error objects are the foundation of exception handling.

  • EvalError: The EvalError function indicates the error that occurred in the eval() function. It’s a global function that evaluates the JavaScript string. JavaScript does not throw this exception anymore.
  • RangeError: RangeError exceptions occur when a numeric value is outside the specified range.
  • ReferenceError: A ReferenceError exception occurs when undeclared variables are used. These exceptions commonly occur due to spelling errors on variables.
  • Syntax Error: A Syntax Error exception occurs when JavaScript language rules get broken.
  • TypeError: A TypeError exception occurs when a value is different from the one expected.
  • URIError: A URIError exception is raised by encodeURI() and decodeURI() methods.

How to handle exceptions in JavaScript

Know that we now understand what exceptions are. It’s time to learn how to handle them to stop our code from crashing. JavaScript handles exceptions in try-catch-finally statements and throw statements.

Key Terms

  • A try-catch-finally statement is a code or program that handles exceptions.
  • The try clause runs the code that generates exceptions.
  • The catch clause catches exceptions that are thrown.
  • A finally clause always gets executed.
  • The throw statement generates exceptions.

To have a complete source code, use this HTML code. Insert the JavaScript code inside the script tag to understand how each exception handling statement works.

 html lang="en"> head>  meta charset="UTF-8">  meta name="viewport" content="width=device-width, initial-scale=1.0">  title>Try-Catch-Finally Statementtitle>  head> body>  script type="text/JavaScript">script>  p>Click the button to see the outputp>  button type="button" onclick="myFunction()">Click Herebutton>  body>  html> 

Throw statements

The throw statement is to raise your built-in exceptions.

Below is an example of a throw statement:

function myFunction()   const x = 50;  const y = 0;  try   if (y === 0)   throw ("This is division by zero error");  > else   const z = x / y;  >  > catch (error)   alert("Error: " + error);  > > 

Try catch statements

The try clause has the main code that may generate exceptions. If an exception is raised, the catch clause gets executed.

Here is an example of a try-catch statement:

function myFunction()   const j = 70;  try   allert("The value of j is : " + j);  > catch (error)   alert("Error: " + error.message);  > > 

In the example above, we have made a typo error while calling the in-built alert() function. We have misspelled alert to produce an error deliberately. The catch clause catches the error and executes the code.

Try catch finally statements

The finally statement is the last block to be executed. It executes after try and catch clauses.

Here is an example of try-catch-finally statements:

function myFunction()   const j = 70;  try   alert("The value of j is : " + j);  > catch (error)   alert("Error: " + error.message);  > finally   alert("Finally: Finally gets executed")  > > 

Wrapping up

In this article we have learned what exception handling is the different types of errors, and the error objects in JavaScript. We have gone over how we handle exceptions in JavaScript. I hope this article has helped you understand the concept of handling exceptions in JavaScript.

Peer Review Contributions by: Linus Muema

Источник

What are the Different Types of Errors in JavaScript?

Javascript Course - Mastering the Fundamentals

In the above example, an opening bracket is missing in the code, which invokes the Syntax error constructor.

  1. Reference Error — In a case where a variable reference can’t be found or hasn’t been declared, then a Reference error occurs.
  1. Type Error — An error occurs when a value is used outside the scope of its data type.
  1. Evaluation Error — Current JavaScript engines and EcmaScript specifications do not throw this error. However, it is still available for backward compatibility. The error is called when the eval() backward function is used, as shown in the following code block:
  1. RangeError — There is an error when a range of expected values is required, as shown below:
  1. URI Error — When the wrong character(s) are used in a URI function, the error is called.
  1. Internal Error — In the JS engine, this error occurs most often when there is too much data and the stack exceeds its critical size. When there are too many recursion patterns, switch cases, etc., the JS engine gets overwhelmed.

Output: Its output will be like InternalError .

What are Errors in JavaScript?

JavaScript code can encounter different errors when it is executed. Errors can be caused by programming mistakes, incorrect input, or other unforeseeable events.

Errors in programming can be divided into two types. These are:

  1. Program Error: — In this case, the program might need to handle this error through its error handlers. An example could be network disconnection, timeout error, etc.
  2. Developer Error: — The programmer has caused an error. It can be a syntax error, a logical error, a semantic error, etc.

The try. catch. finally Statement

Exception handling has been added to JavaScript in recent versions. Exceptions are handled by JavaScript’s try. catch. finally construct and throw operator.
Syntax

Examples of errors in JavaScript

After the try block, there must either be a catch block or a finally block (or both). The catch block is executed if an exception occurs in the try block. After try/catch, finally is executed unconditionally. Let’s see an example:

Output: The below statements will be shown in an alert box.

The throw statement can be used to raise built-in exceptions or your customized ones.

Output: The below statement will be shown in an alert box.

The onerror() Method

In JavaScript, error handling was simplified by the onerror event handler. If there is an exception on the page, the error event will be fired on the window object.

There are three pieces of information provided by the onerror event handler that identifies the error’s exact nature.

Error message − A message similar to the one displayed by the browser when an error occurs. URL − The file where the error occurred.

Line number− This is the line number in the URL where the error occurred.

Conclusion

  • An error is a statement that interferes with the proper operation of the program.
  • There are 7 types of JavaScript errors: Syntax error , Reference Error , Type Error , Evaluation Error , RangeError , URI Error and Internal Error .
  • Errors in Javascript can be handled using the try. catch. finally construct as well as the throw operator .
  • The article allows you to easily identify the source of an error, whether it occurs in your terminal or browser .

See Also

Источник

Оцените статью