Skip to content Skip to sidebar Skip to footer

Javascript Try/catch

I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch b

Solution 1:

Try this the new RegExp is throwing the exception

Regex

<scripttype="text/javascript"charset="utf-8">var grep;

            try {
                    grep = newRegExp("gr[");
            }
            catch(e) {
                    alert(e);

            }
            try
            {
                    var results = grep.exec('bob went to town');
            }
            catch (e)
            {
                    //Do nothing?
            }

            alert('If you can see this then the script kept going');
    </script>

Solution 2:

The problem is with this line:

var grep = newRegExp('gr[');

'[' is a special character so it needs to be escaped. Also this line is not wrapped in try...catch, so you still get the error.

Edit: You could also add an

alert(e.message);

in the catch clause to see the error message. It's useful for all kind of errors in javascript.

Edit 2: OK, I needed to read more carefully the question, but the answer is still there. In the example code the offending line is not wrapped in the try...catch block. I put it there and didn't get errors in Opera 9.5, FF3 and IE7.

Solution 3:

var grep, results;

try {
    grep = newRegExp("gr[");
    results = grep.exec('bob went to town');
}
catch(e) {
    alert(e);
}
alert('If you can see this then the script kept going');

Solution 4:

putting the RegExp initialization inside the try/catch will work (just tested in FireFox)

var grep, results;

try
{
    grep = newRegExp("gr["); // your user input here
}
catch(e)
{
    alert("The RegExpr is invalid");
}

// do your stuff with grep and results

Escaping here is not the solution. Since the purpose of this snippet is to actually test a user-generated RegExpr, you will want to catch [ as an unclosed RegExpr container.

Solution 5:

your RegExp doesn't close the [

In my FireFox, it never returns from the constructor -- looks like a bug in the implementation of RegExp, but if you provide a valid expression, it works

Post a Comment for "Javascript Try/catch"