Lỗi trong javascript

Câu lệnh throw đưa ra một ngoại lệ do người dùng định nghĩa. Việc thực thi chức năng hiện tại sẽ dừng lại (các câu lệnh sau throw sẽ không được thực thi) và quyền kiểm soát sẽ được chuyển đến khối catch đầu tiên trong ngăn xếp cuộc gọi. Nếu không có khối catch nào tồn tại giữa các chức năng của người gọi, chương trình sẽ kết thúc

Show

    throw expression
    

    throw 'Error2'; // generates an exception with a string value
    throw 42;       // generates an exception with the value 42
    throw true;     // generates an exception with the value true
    throw new Error('Required');  // generates an error object with the message of Required
    
    0

    Các biểu hiện để ném

    Sử dụng câu lệnh throw để đưa ra một ngoại lệ. Khi bạn ném một ngoại lệ,

    throw 'Error2'; // generates an exception with a string value
    throw 42;       // generates an exception with the value 42
    throw true;     // generates an exception with the value true
    throw new Error('Required');  // generates an error object with the message of Required
    
    0 chỉ định giá trị của ngoại lệ. Mỗi điều sau đây ném một ngoại lệ

    throw 'Error2'; // generates an exception with a string value
    throw 42;       // generates an exception with the value 42
    throw true;     // generates an exception with the value true
    throw new Error('Required');  // generates an error object with the message of Required
    

    Cũng lưu ý rằng câu lệnh throw bị ảnh hưởng bởi vì không có dấu kết thúc dòng nào giữa từ khóa throw và biểu thức được cho phép

    Bạn có thể chỉ định một đối tượng khi ném một ngoại lệ. Sau đó, bạn có thể tham khảo các thuộc tính của đối tượng trong khối catch. Ví dụ sau tạo một đối tượng kiểu

    throw 'Error2'; // generates an exception with a string value
    throw 42;       // generates an exception with the value 42
    throw true;     // generates an exception with the value true
    throw new Error('Required');  // generates an error object with the message of Required
    
    5 và sử dụng nó trong câu lệnh throw

    function UserException(message) {
      this.message = message;
      this.name = 'UserException';
    }
    function getMonthName(mo) {
      mo--; // Adjust month number for array index (1 = Jan, 12 = Dec)
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
        'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      if (months[mo] !== undefined) {
        return months[mo];
      } else {
        throw new UserException('InvalidMonthNo');
      }
    }
    
    let monthName;
    
    try {
      // statements to try
      const myMonth = 15; // 15 is out of bound to raise the exception
      monthName = getMonthName(myMonth);
    } catch (e) {
      monthName = 'unknown';
      console.error(e.message, e.name); // pass exception object to err handler
    }
    

    Ví dụ sau kiểm tra một chuỗi đầu vào cho một U. S. Mã Bưu Chính. Nếu mã zip sử dụng định dạng không hợp lệ, câu lệnh ném sẽ đưa ra một ngoại lệ bằng cách tạo một đối tượng kiểu

    throw 'Error2'; // generates an exception with a string value
    throw 42;       // generates an exception with the value 42
    throw true;     // generates an exception with the value true
    throw new Error('Required');  // generates an error object with the message of Required
    
    7

    /*
     * Creates a ZipCode object.
     *
     * Accepted formats for a zip code are:
     *    12345
     *    12345-6789
     *    123456789
     *    12345 6789
     *
     * If the argument passed to the ZipCode constructor does not
     * conform to one of these patterns, an exception is thrown.
     */
    class ZipCode {
      static pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
      constructor(zip) {
        zip = String(zip);
        const match = zip.match(ZipCode.pattern);
        if (!match) {
          throw new ZipCodeFormatException(zip);
        }
        // zip code value will be the first match in the string
        this.value = match[0];
      }
      valueOf() {
        return this.value;
      }
      toString() {
        return this.value;
      }
    }
    
    class ZipCodeFormatException extends Error {
      constructor(zip) {
        super(`${zip} does not conform to the expected format for a zip code`);
      }
    }
    
    /*
     * This could be in a script that validates address data
     * for US addresses.
     */
    
    const ZIPCODE_INVALID = -1;
    const ZIPCODE_UNKNOWN_ERROR = -2;
    
    function verifyZipCode(z) {
      try {
        z = new ZipCode(z);
      } catch (e) {
        const isInvalidCode = e instanceof ZipCodeFormatException;
        return isInvalidCode ? ZIPCODE_INVALID : ZIPCODE_UNKNOWN_ERROR;
      }
      return z;
    }
    
    a = verifyZipCode(95060);         // returns 95060
    b = verifyZipCode(9560);          // returns -1
    c = verifyZipCode('a');           // returns -1
    d = verifyZipCode('95060');       // returns 95060
    e = verifyZipCode('95060 1234');  // returns 95060 1234
    

    Bạn có thể sử dụng throw để viết lại một ngoại lệ sau khi bắt được nó. Ví dụ sau bắt một ngoại lệ có giá trị số và chạy lại nếu giá trị đó lớn hơn 50. Ngoại lệ được viết lại lan truyền đến chức năng kèm theo hoặc đến cấp cao nhất để người dùng nhìn thấy nó