What are the standard practices for throwing JavaScript Exceptions?

前端 未结 3 1741
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 18:58

w3schools says that exceptions can be strings, integers, booleans, or objects, but the example given doesn\'t strike me as good practice, since exception type checking is do

3条回答
  •  悲哀的现实
    2021-01-03 19:35

    You could try Dean Edwards' Base project. It emulates class inheritance in javascript, so using it would enable you to subclass the Error type. You can't catch different type of errors in javascript (since it is not a strong typed language), but you could determine the type of Error which was thrown, and add logic for that specific type, like so:

    try {
    
      // do something
    
    } catch (e) {
    
      if (e instanceof NullPointerError) {
    
        // handle nullpointer exception
    
      } else if (e instanceof RuntimeError) {
    
        // handle runtime exception
    
      } else {
    
        // regular exception
    
      }
    } 
    

    Of course in this code I assume you have declared the NullPointerError and RuntimeError classes as subclasses of Error.

提交回复
热议问题