您不能使用try-catch块来处理JavaScript中的语法错误,因为在解析代码时会抛出该错误。
使用window.onerror,如以下代码所示-
<html> <head> <script> window.onerror = function(e) { document.write('Error: ', e, '</br>') }; </script> <script> document.write('x'x') </script> </head> <body> </body> </html>
注–确保错误功能在单独的<script>标记中定义。