Javascript 尝试/捕获 [英] Javascript Try/Catch

查看:23
本文介绍了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 block but alas nothing happens.

如果有帮助,我正在运行 jQuery,但下面的代码没有它,因为我猜它比那更基本一点.

If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that.

是的,我知道我不是在逃避[",这是故意的,也是问题的重点.我正在接受用户输入,我想找到一种方法来解决此类问题,而不会让应用程序崩溃.

Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>Regex</title>

    <script type="text/javascript" charset="utf-8">
        var grep = new RegExp('gr[');

        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>
</head>
<body>

</body>
</html>

推荐答案

试试这个新的 RegExp 抛出异常

Try this the new RegExp is throwing the exception

正则表达式

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

            try {
                    grep = new RegExp("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>

这篇关于Javascript 尝试/捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆