JAVA SCRIPT
June 3, 2026 1 min read

Exception handling in javascript

HS
HEMANT SINGH
Technical Writer & Educator

Exception handing is used to handle errors in js program.

 

try

A block where we write a code in which an error can occur

 

catch

This block handle the error with an object

 

finally

This block run always

 

throw 

This keyword is used to define the new error which will be catch by the catch block

 

example

 

function sum(a, b){

	var c;
	a=Number(a)
	b=Number(b)

	try{
		if(a<0){
			throw "a is less than 0" 
		}

		if(b<0){
			throw "b is less than 0"
		}

		c=a+b;
		console.log("sum:"+c);
	}
	catch(err){
		console.log(err);
	}
}
sum(-1, 10);
sum(10, 20);