throw
Câu lệnh throw
sẽ đưa ra một exception theo cách chúng ta định nghĩa. Các câu lệnh phía sau throw
sẽ không được chạy, và sẽ gọi hàm callback catch
đầu tiên tìm thấy. Nếu không có hàm catch
, chương trình sẽ không chạy nữa.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Source này được lưu trên GitHub repository. Nếu muốn đóng góp cho ví dụ này, bạn clone https://github.com/mdn/interactive-examples và gởi lên pull request.
Cú pháp
throw expression;
expression
- Một diễn giải.
Giải thích
Sử dụng câu lệnh throw
để đưa ra một exception. Giá trị của expression trả về có thể string, number, boolean, hay Object. Mỗi câu throw
chỉ trả về một exception
throw 'Error2'; // 1 exception dạng string
throw 42; // 1 exception giá trị 42
throw true; // 1 exception với giá trị boolean là true
throw new Error('Required'); // tạo một error object với nội dung Required
Câu lệnh throw
tuân thủ nguyên tắc automatic semicolon insertion (ASI) , nghĩa là không được phép xuống dòng giữa từ khóa throw
và expression
.
Ví dụ
Throw một object
Exception có thể là một object. Lúc này có thể tham chiếu đến các property của object bên trong khối lệnh catch
. Ví dụ sau, tạo một object với kiểu là UserException
và sử dụng nó trong câu throw
.
function UserException(message) {
this.message = message;
this.name = 'UserException';
}
function getMonthName(mo) {
mo = mo - 1; // Thay đổi giá trị của index array tương ứng cho tháng (1 = Jan, 12 = Dec)
var 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');
}
}
try {
// statements to try
var myMonth = 15; // 15 nằm ngoài giá trị cho phép
var monthName = getMonthName(myMonth);
} catch (e) {
monthName = 'unknown';
console.log(e.message, e.name); // truyền exception object vào câu lệnh xử lý nếu có lỗi
}
Một ví dụ khác sử dụng object
Trong ví dụ sau, kiểm tra input, chỉ cho phép là giá trị U.S. zip code. Nếu giá trị zip code này không đúng format, throw một exception object là ZipCodeFormatException
.
/*
* 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.
*/
function ZipCode(zip) {
zip = new String(zip);
pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
if (pattern.test(zip)) {
// giá trị zip code value sẽ là giá trị đầu tiên khớp trong string
this.value = zip.match(pattern)[0];
this.valueOf = function() {
return this.value
};
this.toString = function() {
return String(this.value)
};
} else {
throw new ZipCodeFormatException(zip);
}
}
function ZipCodeFormatException(value) {
this.value = value;
this.message = 'does not conform to the expected format for a zip code';
this.toString = function() {
return this.value + this.message;
};
}
/*
* Đoạn script validate address theo kiểu US addresses.
*/
const ZIPCODE_INVALID = -1;
const ZIPCODE_UNKNOWN_ERROR = -2;
function verifyZipCode(z) {
try {
z = new ZipCode(z);
} catch (e) {
if (e instanceof ZipCodeFormatException) {
return ZIPCODE_INVALID;
} else {
return 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 exception
Chúng ta có thể sử dụng throw
để rethrow một exception sau khi đã catch nó. Trong ví dụ sau, catch lại exception nếu là giá trị lớn hơn 50 thì rethrow. Exception này sẽ được đưa lên hàm trên một cấp hoặc lên trên cùng cho các hàm catch khác.
try {
throw n; // throws một exception với giá trị là số
} catch (e) {
if (e <= 50) {
// câu lệnh xử lý cho exception từ 1-50
} else {
// không có xử lý cho trường hợp exception này, rethrow
throw e;
}
}
Specification
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition (ECMA-262) | Standard | Khởi tạo. Hiện thực trong JavaScript 1.4 |
ECMAScript 5.1 (ECMA-262) The definition of 'throw statement' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'throw statement' in that specification. |
Standard | |
ECMAScript (ECMA-262) The definition of 'throw statement' in that specification. |
Living Standard |
Trình duyệt hổ trợ
BCD tables only load in the browser