Exception
  • try ... catch ... finally
  • throw, throw exception
  • try ... catch ... finally
    try
    {
    	addalert("Welcome to Javascript ...");
    }
    catch(err)
    {
    	console.log("Catch error ...");
    	console.log(err);
    }
    finally
    {
    	console.log("Finally statements ...");
    }
    		
    throw
    <input id="demo" type="text" onchange="validate()">
    <script type="text/javascript">
    function f()
    {
    	var x = document.getElementById("demo").value;
    	if (x == "") throw "Empty";
    	if (isNaN(x)) throw "Not a Number ...";
    }
    
    function validate()
    {
    	try{
    		f();
    	}
    	catch(err)
    	{
    		console.log(err);
    		return;
    	}
    		console.log("Input is legal ...");
    	}
    </script>
    		
    Error Properties
  • name, error name
  • message, error message
  • onerror( ) Method
  • The onerror event handler was the first feature to facilitate error handling in JavaScript
  • The error event is fired on the window object whenever an exception occurs on the page
  • <html> 
       <head> 
          <script type = "text/javascript"> 
             function myFunc()
             {
                throw new Error("Erorr ...");
             }
    
             window.onerror  =  function (msg, url, line) {  
                document.write ("An error occurred.");
                console.log(msg); // Error Message
                console.log(url); // URL
                console.log(line); // Line Number
             } 
          </script> 
       </head> 
    
       <body> 
          <p>Click the following to see the result:</p> 
          <form> 
             <input type = "button" value = "Click Me" onclick = "myFunc();" /> 
          </form> 
       </body> 
    </html> 
    		
    Custom Errors
    function MyError(message) { 
       this.name = 'MyError'; 
       this.message = message || 'Error raised with default message'; 
    }
    
    function f() {throw new MyError("Error ...");}
    function f2() {throw new MyError();} // use the default error message
    
    try
    {
    	f();
    }
    catch (e)
    {
    	console.log(e.name);
    	console.log(e.message);
    }
    
    try
    {
    	f2();
    }
    catch (e)
    {
    	console.log(e.name);
    	console.log(e.message);
    }
    		
    Error Types
  • EvalError, An error has occurred in the eval() function
  • RangeError, A number "out of range" has occurred
  • ReferenceError, An illegal reference has occurred
  • SyntaxError, A syntax error has occurred
  • TypeError, A type error has occurred
  • URIError, An error in encodeURI() has occurred
  • Reference
  • Tutorialspoint