- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
NodeJS - Exception Handling in eventful Code
An exception is a type of an event, that occurs while executing or running a program that stops the normal flow of the program and returns to the system. When an exception occurs the method creates an object and gives it to the runtime system. This creating an exception and giving it to the runtime system is known as throwing an Exception.
We need to handle these Exceptions to handle any use case and prevent the system from crashing or performing an unprecedented set of instructions. If we donot handle or throw exceptions, the program may perform strangely.
Exception handling in Synchronous Program
Here, we will learn how to handle exceptions in a eventful flow of program. In an eventful flow of program, an error can occur anywhere. Therefore, instead of throwing the error, you need to fire the error event instead.
Example
// Definite our Divide Number Event var events = require("events") var DivideNumber = function(){ events.EventEmitter.call(this) } require('util').inherits(DivideNumber, events.EventEmitter) // Add the divide function DivideNumber.prototype.divide = function(x, y){ // if error condition occurs ? if ( y === 0 ) { // "throw" the error safely by emitting it var err = new Error("Can't divide by zero") this.emit("error", err) } else { // If No error occurrs, return the result this.emit("Number divided", x, y, x/y) } // Return the event chain return this; } // Create our divider and listen for errors var divideNo = new DivideNumber() divideNo.on('error', function(err){ // handle the error safely console.log(err) }) divideNo.on('Number divided', function(x, y, result){ console.log(x+"/"+y+"="+result) }) // Dividing the number divideNo.divide(10, 5).divide(10, 0)
Output
- Related Articles
- NodeJS - Exception Handling in Asynchronous Code
- NodeJS - Exception Handling in Synchronous Code
- Exception handling in PowerShell
- Exception Handling Basics in C++
- What is exception handling in Python?
- What is exception handling in C#?
- Exception Handling in C++ vs Java
- What is Exception Handling in PHP ?
- C# Exception Handling Best Practices
- PHP Exception Handling with finally
- Exception handling with method overriding in Java.
- Exception handling and object destruction in C++
- Importance of Proper Exception Handling in Java
- Nested try blocks in Exception Handling in Java
- C++ program to demonstrate exception handling
