Hướng dẫn throw error javascript - ném lỗi javascript

Câu lệnh throw ném một ngoại lệ do người dùng xác định. Việc thực hiện hàm hiện tại sẽ dừng (các câu lệnh sau throw sẽ không được thực thi) và điều khiển 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 tồn tại giữa các chức năng của người gọi, chương trình sẽ chấm dứt.throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

Thử nó

Cú pháp

expression

Biểu hiện để ném.

Sự mô tả

Sử dụng câu lệnh throw để ném một ngoại lệ. Khi bạn ném một ngoại lệ, expression 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 chèn dấu chấm phẩy (ASI) tự động là không có trình kết thúc dòng giữa từ khóa throw và biểu thức được cho phép.

Ví dụ

Ném một đối tượng

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

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
}
4 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
}

Một ví dụ khác về việc ném một đối tượng

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

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
}
6.

/*
 * 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

Rethrow một ngoại lệ

Bạn có thể sử dụng throw để tái hiện một ngoại lệ sau khi bạn bắt được nó. Ví dụ sau đây có một ngoại lệ với giá trị số và phát triển lại nếu giá trị trên 50. Ngoại lệ rethrown truyền lê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ó.

try {
  throw n; // throws an exception with a numeric value
} catch (e) {
  if (e <= 50) {
    // statements to handle exceptions 1-50
  } else {
    // cannot handle this exception, so rethrow
    throw e;
  }
}

Thông số kỹ thuật

Sự chỉ rõ
Đặc tả ngôn ngữ Ecmascript # Sec-Suss-Statement
# sec-throw-statement

Tính tương thích của trình duyệt web

Bảng BCD chỉ tải trong trình duyệt

Xem thêm