Categories
ECMAScript Javascript

Error Handling

/**
 * Runtime Error handling can be done by throw, try..catch..finally 
 *  
 */

//Following type of javascript error objects are already

//EvalError - results from eval() function
//RangeError - results when value is outside valid range
//ReferenceError - results when dereferencing when invalid reference
//SyntaxError - results when syntax error in parsing code
//TypeError - results when variable is of invalid type
//URIError - results when encodeURI(), decodeURI() are passed invalid parameters

//throw syntax
//throw new Error([message])
//throw([message])

//try catch finally demo
var num1=2;
var num2=0;
try{
	//code that may throw runtime error
	if(num2==0){
		throw new SyntaxError("Divide by zero not allowed");//this error will throw error because num2 is ZERO.
	}
	var result = num1/num2; 
	console.log("result is ::"+result);//this statement is not executed if previous statement is ERROR.
}catch(e){
	//catch block will contain code to handle situation in case of error situation
	console.log("Error :",e);
}finally{
	//finally will contain block of code which to be executed in any case error or not.
	console.log("Code execution is complete");
}

//create custom Error type
function CustomError(message){
	this.name ="customError";
	this.message = message || "this is custom error";
}

//try catch finally demo
var num1=2;
var num2=0;
try{
	//code that may throw runtime error
	if(num2==0){
		throw new CustomError();//this error will throw error because num2 is ZERO.
	}
	var result = num1/num2; 
	console.log("result is ::"+result);//this statement is not executed if previous statement is ERROR.
}catch(e){
	//catch block will contain code to handle situation in case of error situation
	console.log("Error :",e);
}finally{
	//finally will contain block of code which to be executed in any case error or not.
	console.log("Code execution is complete");
}


Output

Leave a comment

Design a site like this with WordPress.com
Get started