zoukankan      html  css  js  c++  java
  • 【repost】JS错误类型的学习

    SyntaxError是解析代码时发生的语法错误

    // 变量名错误 
    var 1a; 
    // 缺少括号 
    console.log 'hello');

    (2)ReferenceError

    ReferenceError是引用一个不存在的变量时发生的错误。

    unknownVariable 
    // ReferenceError: unknownVariable is not defined

    另一种触发场景是,将一个值分配给无法分配的对象,比如对函数的运行结果或者this赋值。

    console.log() = // ReferenceError: Invalid left-hand side in assignment 
    this = // ReferenceError: Invalid left-hand side in assignment

    上面代码对函数console.log的运行结果和this赋值,结果都引发了ReferenceError错误

    (3)RangeError

    RangeError是当一个值超出有效范围时发生的错误。主要有几种情况,一是数组长度为负数,二是Number对象的方法参数超出范围,以及函数堆栈超过最大值。

    new Array(-1) 
    // RangeError: Invalid array length 
    (1234).toExponential(21) 
    // RangeError: toExponential() argument must be between 0 and 20

    (4)TypeError

    TypeError是变量或参数不是预期类型时发生的错误。比如,对字符串、布尔值、数值等原始类型的值使用new命令,就会抛出这种错误,因为new命令的参数应该是一个构造函数。

    new 123 
    //TypeError: number is not a func 
    var obj = {}; obj.unknownMethod() 
    // TypeError: undefined is not a function

    上面代码的第二种情况,调用对象不存在的方法,会抛出TypeError错误。

    (5)URIError

    URIError是URI相关函数的参数不正确时抛出的错误,主要涉及encodeURI()、decodeURI()、encodeURIComponent()、decodeURIComponent()、escape()和unescape()这六个函数。

    decodeURI('%2') 
    // URIError: URI malformed

    (6)EvalError

    eval函数没有被正确执行时,会抛出EvalError错误。该错误类型已经不再在ES5中出现了,只是为了保证与以前代码兼容,才继续保留。

    以上这6种派生错误,连同原始的Error对象,都是构造函数。开发者可以使用它们,人为生成错误对象的实例。

    new Error("出错了!"); 
    new RangeError("出错了,变量超出有效范围!");
    new TypeError("出错了,变量类型无效!");

    上面代码表示新建错误对象的实例,实质就是手动抛出错误。可以看到,错误对象的构造函数接受一个参数,代表错误提示信息(message)。

    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    在学习ES6的过程中,一路爬行errors

    1.let命令

    {
          let a = 'secret';
          function f() {
                console.log(a);
          }
    }
    f() // 报错

    Uncaught ReferenceError: f is not defined 
    引用错误:f 未定义

    • caught 是 catch 的过去分词形式,过去式形式
    • ReferenceError (引用错误,reference:谈及,查阅)
    • defined 有定义的;清晰的;
    1. const 命令
    const PI = 3.1415
    PI=3;
    console.log(PI);

    Uncaught TypeError: Assignment to constant variable 
    类型错误:指派 常数 为 变量

    • Assignment 指派
    • constant 常数
    • variable 变量;变化的
    function constantize(obj){
          console.log(obj);
    }
    constantize({a=1,b=0});

    Uncaught SyntaxError: Invalid shorthand property initializer 
    语法错误:简称的属性初始化不完整

      • Syntax 语法;句法
      • Invalid 有病的;伤残的
      • shorthand 简称;速记法的;速记
      • initializer 初始化
  • 相关阅读:
    innodb文件
    Innodb 存储引擎
    第二章 flex输入输出结构
    第二章 flex输入输出
    第二章 flex处理二义性
    第一章 flex单词计数程序
    Compile SQLite3 from individual files
    标 题: [心得]传统IT转互联网面试经验分享
    【设计模式】二:策略模式
    python 爬虫第三例--爬美女图片
  • 原文地址:https://www.cnblogs.com/neil080320/p/6259980.html
Copyright © 2011-2022 走看看