Javascript 处理XMLHttpRequest异常

Javascript 处理XMLHttpRequest异常,javascript,xmlhttprequest,Javascript,Xmlhttprequest,鉴于此代码 var xhr = new XMLHttpRequest(); xhr.open('get', 'http://example.com', false); alert(0); xhr.send(); alert(1); 如果http://example.com是一个跨域URL,它将在xhr.send()处导致异常。然后,永远不会到达警报(1) 我如何编写它,即使它是一个“坏”URL,它也会一直写到最后? var xhr = new XMLHttpRequest(); xh

鉴于此代码

var xhr = new XMLHttpRequest();
xhr.open('get', 'http://example.com', false);   
alert(0);
xhr.send();  
alert(1);
如果
http://example.com
是一个跨域URL,它将在
xhr.send()
处导致异常。然后,永远不会到达
警报(1)

我如何编写它,即使它是一个“坏”URL,它也会一直写到最后?

var xhr = new XMLHttpRequest();
xhr.open('get', 'http://example.com', false);   
alert(0);
try {
    xhr.send();
} catch (e) {
   console.log(e);
}  
alert(1);