Question: I was trying to test whether certain file exist using javascript.(don't want to use Ajax). Want to use catch try to handle ERR\_FILE\_NOT\_FOUND error. I tried 

```
   try{
            img.attr('src', url)
        }catch(err){
            console.log("file"+ url + " doesn't exist");
        }

```

but it doesn't catch up the error.How do I catch ERR\_FILE\_NOT\_FOUND error?

Answer: 
~~Setting the image attribute src isn't going to throw anything based on the results of the file existing or not, it will just simply show the image or not show it.~~

~~You might be able to check the size of the image after it's done loading and see if it is 0 width, but this is still just a hack and might only work for images.~~

Your best bet is jQuery with ajax and use a simple: 

```
$.get("/path/to/file", function(data, status) {  
   console.log("File request status: "+status); 
});

```

**EDIT:**

You might want to check the onerror event like in the comment, you could use the html like: 

`<img onerror="onerrFunction()">`

or 

js: `imgObject.onerror = function(){}`

---

The error you are referring to as 'ERR\_FILE\_NOT\_FOUND' I assume you are finding from a browser such as chrome in the developer console like so: 

![screenshot](https://i.stack.imgur.com/qpXuB.png)

However, this is not a javascript erro being thrown, so you cannot catch it with js code. This is just a browser error to help debug your code. There might be other ways to catch these kinds of errors but as for what you are asking, that probably isn't in the scope of the question.
The only way I found is making a fake request to check the file is wherever exist or not like this:

```
  var request;
  if(window.XMLHttpRequest)
      request = new XMLHttpRequest();
  else
  request = new ActiveXObject("Microsoft.XMLHTTP");
  request.open('GET', url, false);
  request.send();
  // the object request will be actually modified
  if (request.status === 404) {
      console.log("file"+ url + " doesn't exist");
  } 
  else
  {
      img.attr('src', url)
  }

```

Notice: It only works with same origin, so if you need to check the file in other origins. you need to use Ajax or backend languages.