6

I know that using following block, it is able to catch an Exception.

try{
    // Code
}catch(err){
    alert(err.message);
}

Say, I want to catch a NumberFormatException. How can I catch a specific Exception using JavaScript?
(I actually want to catch NumberFormatException, InterruptedException, ConnectException which are well defined in Java)

simonzack
  • 19,729
  • 13
  • 73
  • 118
vidulaJ
  • 1,232
  • 1
  • 16
  • 31
  • 1
    JavaScript is not Java. There is no `NumberFormatException` in JavaScript, nor `InterruptedException`, nor `ConnectException`. JavaScript has as much in common with Java as a manhole has with a man. If you wish to know whether a string is a well-formed number or not, use `isNaN()` on the result of `parseInt()` or `parseFloat()`. – Amadan Oct 14 '14 at 10:08
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Example:_Handling_a_specific_error – Prabhu Murthy Oct 14 '14 at 10:09
  • this thread has more answers https://stackoverflow.com/questions/1433558/handling-specific-errors-in-javascript-think-exceptions – Dominic Johnston Whiteley Jul 13 '22 at 00:42

1 Answers1

8

Javascript has no standard way of doing this.

try{
    // Code
}catch(err){
    if(err instanceof SomeException){
        alert(err.message);
    }
}

Firefox has an extension, which I think is nice and should be more standard.

simonzack
  • 19,729
  • 13
  • 73
  • 118