为什么在这种情况下不会抛出 "object is not defined" 错误?

Why "object is not defined" error not getting thrown in this case?

没有 try-catch,下面的代码片段会抛出 Uncaught ReferenceError: myObj is not defined

try {
  if (myObj !== null && typeof myObj !== "undefined");
} catch (e) {
  document.getElementById('error').innerHTML = e.Message;
}
<p>The error is
  <mark id='error'></mark>
  <p>

为什么 <mark id='error'></mark> 中没有打印错误消息?

e.Message中的消息是小写的:

try {
  if (myObj !== null && typeof myObj !== "undefined");
} catch (e) {
  document.getElementById('error').innerHTML = e.message;
}
<p>The error is
  <mark id='error'></mark>
  <p>

只需从异常对象中删除 Message 属性,只需 e 本身就足够了。

document.getElementById('error').innerHTML = e;

这会起作用

您应该使用 e.message,您得到的是 undefined,因为 e 没有 属性 名称 Message

try {
  if (myObj !== null && typeof myObj !== "undefined");
} catch (e) {
  document.getElementById('error').innerHTML = e.message;
  //  or you can use e directly as well.
}
<p>The error is
  <mark id='error'></mark>
  <p>