Define Exception handling in ES6
Last Updated :
02 Nov, 2021
Exception: Exceptions are unwanted event that basically interrupts the normal flow of program. There are two types of exception in general:-
- Synchronous (eg. runtime errors)
- Asynchronous (eg. system errors)
Exception Handling: Often a times exception happens in a program that causes the program to terminate abruptly or in an unfriendly manner. To handle or to prevent the unanticipated behavior is called Exception Handling. Exception handling deals with synchronous exceptions such as bad user input, nonexisting files, etc. (it includes runtime errors).
Why Exception Handling: Exception handling basically ensures that the program does not terminate abruptly or the flow of the program does not break in an unfriendly manner. Meaningful error reporting is possible and one can generate understandable error reports for users.Â
ES6Â (ECMA Script Programming Language version 6) provides the important feature of exception handling. It is accomplished by using try-block followed by either catch-block or finally-block. As try block doesn't exist alone, they are either followed by a catch block or by finally block. It exists in one of the three forms:-
- try...catch
- try...finally
- try...catch...finally
1. try...catch block: Code or try statements in try block will execute first. Whenever the exception occurs it will be placed in the exception_var and the catch block will execute further.
Syntax:Â
try {
// try statements
// code to run
} catch (exception_var) {
// catch statements
// code to run
}
2. try...finally block: First of all the try statements would be executed. After that finally, statements will be executed. Finally block will always get executed regardless of exception occurred or not.
Syntax:
try {
// try statements
// code to run
} finally {
// finally statements
// code that is always executed
}
3. try...catch...finally block: Â try block executes at first if an exception occurs its value will be placed in exception_var and catch block will get executed after that finally block will get executed. However, finally block will execute regardless of conditions of the exception occurred or not.Â
Syntax:
try {
// try statements
// code to run
} catch (exception_var) {
// catch statements
// code to run if exception occurs
} finally {
// finally statements
// code that is always executed
}
Let's understand with the below examples:
Example 1: Let's take an example of bad user input in which the user divide the problem by zero "0".Â
javascript
<script>
var num = 5;
var de_num = 0;
try {
if(de_num == 0) {
throw "Divide by zero error";
} else {
var sol = num / de_num;
}
} catch(e) {
console.log("Error : " + e);
}
</script>
Output:Â
Error : Divide by zero error
Example 2: Let's take another example in which a reference error is thrown whenever we use a reference of something that we have not declared. In this example, we have not declared the function intentionally and called it directly that will cause ReferenceError.Â
javascript
<script>
try{
ab();
// We have not declared the
// function ab anywhere
} catch(e){
console.log("Error : "+ e.name);
}
</script>
e.name will return the name of the error.
Output:
Error : ReferenceError
Example 3: In our final example we deliberately have written a statement to try to block syntactically wrong. We have not enclosed the string between single quotes properly. It will give us the SyntaxError.
javascript
<script>
try {
eval("alert('ES6 Exception Handling)");
} catch(e){
console.log("Error : " + e.name)
}
</script>
Output :
Error : SyntaxError
Similar Reads
How to define a function in ES6 ?
In this article, we will try to understand basic details which are associated with the function definition, like syntax declaration of a function or some examples associated with different types of functions declarations in ES6 (EcmaScript-6). Let us first understand what exactly the function is an
3 min read
Explain Constants in ES6
JavaScript is the world's most popular lightweight, interpreted compiled programming language. It is also known as a scripting language for web pages. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as
3 min read
Explain sub-classes and inheritance in ES6
Sub-class: A subclass is a class that is derived from the properties and methods of some other class known as the Parent class for that subclass. A subclass allows us to change or update the properties of the parent class without disturbing it. A subclass can contain properties of the parent class a
3 min read
JavaScript Function Definitions
JavaScript functions are declared using the function keyword, either as a declaration or expression. Declarations define named functions, while expressions assign functions to variables. Both enable code reuse and modularity.SyntaxFunction Declarationsfunction functionName( parameters ) { // Stateme
2 min read
Event handler in Angular 6+
Introduction: In Angular 6, event handling is used to hear and capture all the events like clicks, mouse movements, keystrokes and etc. It is an important feature that is present in Angular and it is used in every project irrespective of its size. Syntax: html <HTML element (event) > = functio
2 min read
Difference Between Node Require and ES6 Import And Export
Importing modules makes your code reusable. NodeJS offers two ways to do this: CommonJS (require()) and ES6 modules (import/export). Both achieve the same goalâsharing code, but use different syntax.CommonJS is the older, traditional way. ES6 modules are newer and offer some advantages, but both are
5 min read
Node.js util.inherits() Method
The âutilâ module provides âutilityâ functions that are used for debugging purposes. For accessing those functions we need to call them (by ârequire(âutilâ)â). The util.inherits() (Added in v0.3.0) method is an inbuilt application programming interface of the util module in which the constructor inh
3 min read
How to debug code in ES6 ?
In this article, we are going to learn how to debug a code in ES6. Debugging is the process of finding and resolving the problem or mistake in code due to which it doesn't work as expected. Debugging is an important part of programming that helps programmers to fix the bugs in the code. Checking an
2 min read
What are TypeScript Interfaces?
TypeScript interfaces define the structure of objects by specifying property types and method signatures, ensuring consistent shapes and enhancing code clarity.Allow for optional and read-only properties for flexibility and immutability.Enable interface inheritance to create reusable and extendable
4 min read
Shadowing Properties in JavaScript
Shadowing properties in JavaScript refer to the scenario where a variable declared within a nested scope has the same name as a variable in its outer scope. This can lead to confusion and unexpected behaviour, as the inner variable may "shadow" the outer one, effectively hiding it from the outer sco
2 min read