Exceptions in JavaScript


/ Published in: JavaScript
Save to your folder(s)

An example taken from JavaScript: The good parts showing how to catch an exception.


Copy this code and paste it in your HTML
  1. var sum = function(){
  2. var value = 0;
  3. for(i=0;i<arguments.length;i++){
  4. if(typeof arguments[i] !== 'number'){
  5. throw {
  6. name: 'TypeError',
  7. message: 'That wasn\'t a number fool!'
  8. }
  9. } else {
  10. value += arguments[i];
  11. }
  12. }
  13.  
  14. alert(value);
  15. }
  16.  
  17.  
  18. var sumMe = function(){
  19. try {
  20. sum(45,33,"string",89,12,354, true);
  21. } catch(e){
  22. document.write(e.name + ': ' + e.message);
  23. }
  24. }
  25.  
  26. sumMe();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.