0

I have been reading through the W3Schools tutorials on JavaScript, and am having a hard time understanding why my script is not throwing an exception. I expect it to throw an exception on the call document.getElementById("paragraphs"), because there is no id that equals paraghraphs. Please let me know why it's not throwing an Exception?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Design Patterns</title>
</head>

<body>  

<button type="button" onclick="throwException()">Click Me!</button> 
<p id="paragraph">I am a paragraph</p>

<script>

function throwException(){

try{            
        var errorContainer = document.getElementById("paragraphs").value;               
}catch(err){            
        errorContainer.innerHTML="An error occured...";
        }
}

</script>


</body>
</html>
8
  • 1
    I have been reading through the W3Schools tutorials -- that's your first mistake. :) Commented Nov 12, 2013 at 1:53
  • Try replacing throw "Hey I'm an exception!"; with throw new Error("Hey I'm an exception!");let me know if this helps... :) Commented Nov 12, 2013 at 1:53
  • There's no variable error in the catch block. Did you mean err? Commented Nov 12, 2013 at 1:55
  • I was starting to wonder if W3Shools was sufficient, seems like it leaves all the real details out :) Commented Nov 12, 2013 at 1:59
  • getElementById() doesn't throw an exception when it can't find the ID, it just returns null. Commented Nov 12, 2013 at 1:59

1 Answer 1

2

Your code isn't throwing an exception on var error = document.getElementById("paragraphs"); because document.getElementById() does not throw an exception when the element is not found, instead it returns null. Check this documentation under the "Notes" section.

Also, as indicated in a comment above, W3Schools is not a great resource. It is good for purely beginner activities to learn the very basics, but beyond that it is known to the wider community as a source of bad coding practices and sometimes just plain misinformation.

A much better documentation resource (it doesn't have tutorials, but has much better documentation, at least on Javascript) is the Mozilla Developer Network.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.