throw statement
  
        JS Home  << 
        JS Reference  << 
        throw
  
  Throw a user defined exception.
Description
The throw statement allows us to generate a user defined exception using an expression.
Syntax
| Signature | Description | 
|---|---|
throw expression; | Generate a user defined exception using an expression. | 
Parameters
| Parameter | Description | 
|---|---|
expression | The value of the expression to be thrown. | 
Examples
The code below gives examples of using the throw statement.
// Create our own error object.
function ourError(message) {  
  this.name = 'OurError';  
  this.message = message || 'Default Message Used When No Message Passed';
}  
// Inherit from the Error constructor.
ourError.prototype = new Error();  
ourError.prototype.constructor = ourError;}   
// Throw an error and a message.
try {  
    throw new ourError('A Message we have passed');  
} catch (e) {  
    alert('Our Error: ' + e.name + ' Our Message: ' + e.message);
} finally {  
    alert('A finally statement will always be executed!');
}  
// Throw an error when condition is false.
var aNumber = 5;
  
if (aNumber < 5) {
    alert('This number is ok');
} else {
    
    try {  
      throw new ourError('Invalid number');  
    } catch (e) {  
      alert('Our Error: ' + e.name + ' Our Message: ' + e.message);
    }
} 	  
		
		Related Tutorials
JavaScript Advanced Tutorials - Lesson 2 - Errors
