一、可以用throw语句抛出一个异常并且用try…catch语句捕获处理它

异常类型

一、JavaScript可以抛出任意对象。然而,不是所有对象能产生相同的效果。

throw语句

一、使用throw语句抛出一个异常
二、可以抛出任意表达式而不是特定一种类型的表达式

  1. throw "Erroww" // String type
  2. throw 42 // Number type

三、可以再抛出异常时声明一个对象。就可以在catch块中查询到对象的属性

  1. // Create an object type UserException
  2. function UserException (message){
  3. this.message=message;
  4. this.name="UserException";
  5. }
  6. // Make the exception convert to a pretty string when used as
  7. // a string (e.g. by the error console)
  8. UserException.prototype.toString = function (){
  9. return this.name + ': "' + this.message + '"';
  10. }
  11. // Create an instance of the object type and throw it
  12. throw new UserException("Value too high");

try…catch语句

【见】错误处理 try…catch:https://www.yuque.com/tqpuuk/yrrefz/sx9f9m

使用Error对象

一、见 Error对象:https://www.yuque.com/tqpuuk/yrrefz/lsyd2s