菜鸟笔记
提升您的技术认知

js抛出自定义异常-ag真人游戏

使用抛出异常机制能让代码结构更加的简洁,减少很多的逻辑判断,并且能够得到出错时的详细错误信息,可说是好处多多,今天

要说的就是在js中抛出(throw)异常。

js中可以抛出任何类型的异常,比如数字、字符串甚至布尔值,例如:

也可以抛出自定义的对象,比如:

当然,像大多数的面向对象语言中有内置的exception类一样,js中也有内置的异常类: error 

new error([message[, filename[, linenumber]]])
message
optional. human-readable description of the error.
filename 
optional. the value for the filename property on the created error object. defaults to the name of the file containing the code that called the error() constructor.
linenumber 
optional. the value for the linenumber property on the created error object. defaults to the line number containing the error() constructor invocation.

 简单示例:

自定义异常类并继承error基类:

除了error基类,js中还内置了几种具体的异常类如下:

evalerror
creates an instance representing an error that occurs regarding the global function eval().
internalerror 
creates an instance representing an error that occurs when an internal error in the javascript engine is thrown. e.g. "too much recursion".
rangeerror
creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
referenceerror
creates an instance representing an error that occurs when de-referencing an invalid reference.
syntaxerror
creates an instance representing a syntax error that occurs while parsing code in eval().
typeerror
creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
urierror
creates an instance representing an error that occurs when encodeuri() or decodeuri() are passed invalid parameters.

捕获处理特定的错误类

网站地图