JavaScript: Try/Catch - what am I doing wrong here? - javascript

I am wrapping my code into try/catch blocks and I decided to test it out to see how it works.
Below is a simple snippet of code that will generate a Syntax Error - trigge rHandler
try{
$(document).trigge rHandler('fbload');
}catch(e){
alert(e);
}
However I'm not getting the alert! Instead the error is logged in the console as an Unhandled Syntax Error. I was expecting that any error that is generated inside the Try block will automatically be passed down into the Catch section where I can do anything I want with it? Why does this not appear to be working?

try..catch will catch exceptions which occur at runtime. But Syntax errors occur during parsing time itself. So, when the code
$(document).trigge rHandler('fbload');
is encountered, JavaScript tries to parse the expression. But it couldn't. So it is clueless and fails immediately with SyntaxError and that is why it is not caught by the except block.

Related

How to pass native ReferenceError object stack to console in a JavaScript try catch?

In JavaScript, when using a try catch, how can I get the native Chrome ReferenceError object to the console as it would normally be logged? I can get close by using the Error object's stack property, but it logs the errors differently:
try {
bet you can't run this you dumb computer;
}
catch(error) {
console.log(error.stack);
}
When running the above, I get the following in the console:
While this is slightly helpful, clicking on the line number takes me to the console.log(error.stack) line in the code, not the error.
Without the try catch, the error looks like this:
and clicking on the line number will take me exactly to where the original error occurred. So how can I get this native Chrome error object to pass to the catch and then log to the console so that I can navigate to the original error and line that was thrown as it would normally be without the try catch in place?
I believe it'll work with the error method from the console object:
try {
bet you can not run this you dumb computer;
}
catch(error) {
console.error(error);
}
Hope this helps!

try and catch javascript unexpected identifier

i'm tryin to identify the error i get in a javascrip function in my webpage, so i added
function guardarMisDatos() throws Exception {
try{
...
} catch (Exception e){
alert("error: ", e);
}
but when i open the page, the chrome web console gives me error at
function guardarMisDatos() throws Exception {
and the error type is "Uncaught syntaxerror: unexpected identifier"
where is the error? is it a correct way to check way the function is not fired on the first click?
It is JavaScript not Java. Lose the throws Exception!
Your code looks a lot like Java, not javaScript. The syntax for try/catch in javaScript goes like this:
try {
// do stuff
} catch (e) {
// something bad happened
}
Notice there is no throws and no type on e (since javascript is loosely typed)
Remove "throws Exception" and the catch reference to "Exception". To know what kind of exception it is, look at the e.name property, it'll be one of six things:
EvalError - An error in the eval() function has occurred.
RangeError - ut of range number value has occurred.
ReferenceError - An illegal reference has occurred.
SyntaxError - A syntax error within code inside the eval() function has occurred. All other syntax errors are not caught by try/catch/finally, and will trigger the default browser error message associated with the error. To catch actual syntax errors, you may use the onerror event.
TypeError - An error in the expected variable type has occurred.
URIError - An error when encoding or decoding the URI has occurred (ie: when calling encodeURI()).
These aren't constants, they're the actual string, as in if (e.name.toString()=="TypeError") There are a lot of other good things on the error object too, read more at http://www.javascriptkit.com/javatutors/trycatch2.shtml
Remove the throws Exception from your function definition. You do not need this in JavaScript. Besides that, why would your function ever throw an exception - you already catch it!

Can I throw an exception in Javascript, that stops Javascript execution?

I try to simulate a problem where a script that is loaded from an external url stops execution of any more scripts on my site.
I tried to simulate such a problem by calling a function that does not exits. I can see the error in firebug but different scripts on the page are still executed.
Are there different kinds of errors in Javascripts? If yes: what kind of error stops script execution? I only need this answer for Firefox.
EDIT
This question is easy to misunderstood but Rob W got it: I need to throw an exception and that exception needs to stop further script execution.
Answer to the title: No
Answer to "Are there different kinds of errors in JavaScript**: Yes, see MDN: Error
Syntax errors will prevent a whole script block from being executed,
other errors (TypeErrors, Reference errors) will only stop the execution after the occurrence of the error.
Different <script> blocks are executed separately. You cannot prevent the second block from execution by throwing an error in the first block (Demo: http://jsfiddle.net/WJCEN/).
<script>Example: Syntax error in this script.</script>
<script>console.log('Still executed.')</script>
Also, if an error is caught using try-catch (demo: http://jsfiddle.net/WJCEN/1/), then the error will not even stop the execution a whole block.
try {throw 'Code';}catch(e){}
console.log('Still executed');
There is no general one-fit-all method to stop all code from running. For individual scripts, you can use some tricks to prevent the code from running further.
Example 1 (demo): Temporary overwrite a method
1: <script>window._alert = alert;alert=null;</script>
2: <script>alert('Some code!');confirm('Not executing');</script>
3: <script>alert=_alert;delete window._alert;alert('Done!');</script>
This method is based on the fact that script 2 expects alert to be a function. We have rewritten alert to a non-function property (script 1). Script 2 throws a TypeError, and the second block is skipped.
We restore the original values in script 3.
Example 2 (demo): Define a constant method, which cannot be overwritten.
4. <script>Object.defineProperty(window, 'test',{value:null});</script>
5. <script>var test=function(){alert('Test');};test();alert('What?');</script>
This methods relies on the Object.defineProperty method, to effectively define a constant value. In strict mode, the var test declaration would throw a TypeError: "test is read-only".
When strict mode is not enables, a TypeError will be thrown at test(): "test is not a function" (because we defined test to be constant, in script 4).
Note: The last method is not working correctly with function declarations (see bug #115452, Chrome 17)
Use
try catch finally block
It will do the trick
you can use the error object which support the following two properties:
name: The name of the error.
message: A description of the error.
for example to stop execution you can use : throw new Error("myError");
Are there different kinds of errors in Javascripts?
Besides the generic Error constructor, there are six other core errors in JavaScript:
see here details on these errors.
Stop the execution with
throw new Error('stopIt');
This will also do the trick:
throw 'Stop It!';

Object has no method, error in script w/jQuery

I have
function Student(){
var that=this;
that.SaveChanges=function(){
//.....
}
function init(){
that.SaveChanges1();
}
init();
}
<script type="text/javascript">
$(document).ready(function () {
var student=new Student();
});
</script>
With jquery-1.4.4.min.js, I could not save changes, because I made error, but rest of the application work.
With jquery-1.7.1.min.js I get error Object # has no method 'SaveChanges1' and rest of the application does not work.
OR
that.SaveChanges1 is not a function
[Break On This Error]
(77 out of range 4)
What should I do to work like with jquery-1.4.4.min.js?
I think you should try NOT to make errors in your javascript... It's good that it blows up, at least it warns you that something doesn't work! Perhaps you should try running some javascript or selenium tests and perhaps a jslint check to make sure that you don't break any of your javascript functionality!
If you want to ignore your errors in some parts of your program, you can do so by using exception handling. But, you cannot just blindly ignore all errors because when a portion of your script gets an error, that portion of the script has to stop executing as there is no orderly way to continue execution after an error. The javascript interpreter doesn't know which types of errors are harmless and which types mess up the whole script.
To catch an exception in one part of the script and continue executing other parts, you can add your own exception handling like this:
try {
// your code here that might cause a run-time error
} catch(e) {
// might want to put some debugging code here so you know that an error was thrown
}
// more code here that will execute even if the previous code threw an error
Note: you can use exception handling for run-time execution errors. You cannot use it for syntax errors that prevent compilation of the javascript code because when that happens, the interpreter can't even understand your code.

How to create, design and throw built-in Error objects

UPDATE
[Rewriting question to focus on the problem I am trying to understand.]
Is there a means in JavaScript to throw Exceptions that notify the line number where the problem occurs? Similar to C#'s debugger, if an error is thrown on line 50 then I will be taken to line 50.
For example, according to MDN EvalError represents an error with eval(). So, let's say I have a function that uses eval(). I want to use a specific error that is representative of the problem at hand, EvalError:
//As written here the error implies there is a problem on this line. See Firebug console window
var evalErra = new EvalError('required element missing from evaluation');
var stringFunc = "a=2;y=3;document.write(x*y);";
EvalString(stringFunc);
function EvalString(stringObject) {
//Some arbitrary check, for arguments sake let's say checking for 'x' makes this eval() valid.
if(stringObject.indexOf('x') !== -1) {
throw evalErra;
//throw 'required element missing from evaluation';//This way offers no line number
}
eval(stringFunc);//The problem really lies in the context of this function.
}
If I'm going about this all wrong, then please tell me how I should approach these kinds of issues.
When you throw an error, execution of the current code will stop and JS will work its way back up the execution tree until it finds a catch () which handles the particular type of error being thrown, or gets all the way up to the top of the tree, causing an "unhandled exception" error: You threw an error, and nothing caught it, and now someone's window got broken.
try {
if (true) {
throw 'yup'
}
} catch (e) { // catches all errors
... handle the error
}
When doing error handling you want to do the following
throw new Error("message");
Then if you ever handle this error look at err.stack (firefox/opera/chrome) or err.line (Safari) or err.IE_Y_U_NO_SHOW_ME_ERROR_LINE_NUMBER (IE) to find the line number.
If you want you can subclass Error.

Categories

Resources