var s = null;
var len = s.length; // TypeError:null变量没有length属性
int fd = open("/path/to/file", O_RDONLY);
if (fd == -1) {
printf("Error when open file!");
} else {
// TODO
}
try ... catch ... finally
'use strict';
var r1, r2, s = null;
try {
r1 = s.length; // 此处应产生错误
r2 = 100; // 该语句不会执行
} catch (e) {
alert('出错了:' + e);
} finally {
console.log('finally');
}
console.log('r1 = ' + r1); // r1应为undefined
console.log('r2 = ' + r2); // r2应为undefined
try {
...
} catch (e) {
...
} finally {
...
}
try {
...
} catch (e) {
...
}
try {
...
} finally {
...
}
错误类型
Error派生的TypeError、ReferenceError等错误对象
try {
...
} catch (e) {
if (e instanceof TypeError) {
alert('Type error!');
} else if (e instanceof Error) {
alert(e.message);
} else {
alert('Error: ' + e);
}
}
抛出错误
'use strict';
var r, n, s;
try {
s = prompt('请输入一个数字');
n = parseInt(s);
if (isNaN(n)) {
throw new Error('输入错误');
}
// 计算平方:
r = n * n;
alert(n + ' * ' + n + ' = ' + r);
} catch (e) {
alert('出错了:' + e);
}
var n = 0, s;
try {
n = s.length;
} catch (e) {
console.log(e);
}
console.log(n);