Exceptional Exception Handling in JavaScript       MDN资料

Anything that can go wrong, will go wrong.  Murphy’s law is even applicable to software development.  For non-trivial programs, it’s not a matter of if, but when something will go wrong.  Standards non-compliance, unsupported features, and browser quirks are just a few sources of potential problems facing web developers.  Given all of the things that can go wrong, JavaScript has a surprisingly simple way of dealing with errors(js处理错误的方式很简单,仅仅是程序停下来) ― it just gives up and fails silently.  At least, that’s the behavior seen by the user.  In reality, there is a lot going on under the hood.

When a JavaScript statement generates an error, it is said to throw an exception.(在js中,程序产生错误,叫做抛出异常)  Instead of proceeding to the next statement, the JavaScript interpreter checks for exception handling code.  If there is no exception handler, then the program returns from whatever function threw the exception.  This is repeated for each function on the call stack until an exception handler is found or until the top level function is reached, causing the program to terminate.

Error Objects

When an exception occurs, an object representing the error is created and thrown(当异常发生时,一个表示错误的对象就会被创建和抛出).  The JavaScript language defines seven types of built-in error objects.  These error types are the foundation for exception handling.  Each of the error types is described in detail below.

The Error constructor creates an error object. Instances of Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.

Syntax

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.

standard built-in error types(七种标准的内置错误)

Error

The “Error” type is used to represent generic exceptions(一般错误).  This type of exception is most often used for implementing user defined exceptions.  The topic of creating user defined exceptions will be revisited later in this article.  “Error” objects are instantiated by calling their constructor as shown in the following example.

var error = new Error("error message");

“Error” objects contain two properties, “name” and “message”.  The “name” property specifies the type of exception (in this case “Error”).  The “message” property provides a more detailed description of the exception.  The “message” gets its value from the string passed to the exception’s constructor.  The remaining exception types represent more specific types of errors, but they are all used in the same fashion as the generic “Error” type.

RangeError

Creates an instance representing an error that occurs when a numeric variable or parameter(数值变量或数值参数不在有效范围内) is outside of its valid range.

“RangeError” exceptions are generated by numbers that fall outside of a specified range.  For example, JavaScript numbers have a toFixed() method which takes a “digits” argument representing the number of digits to appear after a decimal point.  This argument is expected to be between 0 and 20 (although some browsers support a wider range).  If the value of “digits” is outside of this range, then a “RangeError” is thrown.  This scenario is shown in the following example.

ReferenceError

A “ReferenceError” exception is thrown when a non-existent variable(当要获取一个“不存在”的变量时) is accessed.  These exceptions commonly occur when an existing variable name is misspelled.  In the example below, a “ReferenceError” occurs when “bar” is accessed.  Note that this example assumes that “bar” does not exist in any active scope when the increment operation is attempted.

SyntaxError

A “SyntaxError” is thrown when the rules(js规则错了,即语法错误) of the JavaScript language are broken.  Developers who are familiar with languages such as C and Java are used to encountering syntax errors during the compilation process.  However, because JavaScript is an interpreted language, syntax errors are not identified until the code is executed.  Syntax errors are unique as they are the only type of exception that cannot be recovered from.  The following example generates a syntax error because the “if” statement is missing a closing curly brace.

TypeError

Creates an instance representing an error that occurs when a variable or parameter is not of a valid type(参数或变量不是有效的类型).

A “TypeError” exception occurs when a value is not of the expected type.  Attempting to call a non-existent object method is a common cause of this type of exception.  The following example creates an empty object named “foo” and then attempts to invoke its bar() method.  Since bar() is not defined, a “TypeError” is thrown upon the attempted invocation.

URIError

A “URIError” exception is thrown by methods such as encodeURI() and decodeURI() when they encounter a malformed URI(即这两个函数碰到了无效的参数).  The following example generates a “URIError” while attempting to decode the string “%”.  The “%” character represents the beginning of a URI escape sequence.  Since nothing follows the “%” in this example, the string is an invalid escape sequence, and therefore a malformed URI component.

EvalError

“EvalError” exceptions are thrown when the eval() function is used improperly.  These exceptions are not used in the most recent version of the EcmaScript standard.  However, they are still supported in order to maintain backwards compatibility with older versions of the standard.

Handling Exceptions(处理错误的过程)

Now that we know what exceptions are, it’s time to learn how to stop them from crashing our programs(js是通过try...catch...finally..处理错误,来以免错误把程序给搞崩溃).  JavaScript handles exceptions via the “try…catch…finally” statement.  A generic example statement is shown below.

try {
// attempt to execute this code
} catch (exception) {
// this code handles exceptions
} finally {
// this code always gets executed
}

The first part of a “try…catch…finally” statement is the “try” clause.  The “try” clause is mandatory(try是必须的,把可能出错的代码块放在try里面), and is used to delimit a block of code that the programmer suspects could generate an exception.  The “try” clause must be followed by one or both of the “catch” and “finally” clauses.

The “catch” Clause

The second part of “try…catch…finally” is the “catch” clause.  The “catch” clause is a block of code that is only executed(只有try部分抛出了异常,catch部分的代码才会执行) if an exception occurs in the “try” clause.  Although the “catch” clause is optional, it isn’t possible to truly handle an exception without one.  This is because the “catch” clause stops the exception from propagating through the call stack, allowing the program to recover.  If an exception occurs within the “try” block, then control is immediately passed to the “catch” clause.  The exception that occurred(控制权和异常对象都会被传递给catch部分) is also passed to the “catch” block for processing.  The following example shows how a “catch” clause is used to handle a “ReferenceError”.  Note that the “ReferenceError” object is available in the “catch” clause via the “exception” variable.

try {
foo++;  // ReferenceError
} catch (exception) {
var message = exception.message; // handle the exception
}

Complex applications can generate a variety of exceptions.  In such cases, the “instanceof” operator can be used to differentiate between the various types of exceptions.  In the following example, assume that the “try” clause can generate several types of exceptions.  The corresponding “catch” clause uses “instanceof” to handle “TypeError” and “ReferenceError” exceptions separately from all other types of errors.

try {
// assume an exception occurs
} catch (exception) {
if (exception instanceof TypeError) {
// Handle TypeError exceptions
} else if (exception instanceof ReferenceError) {
// Handle ReferenceError exceptions
} else {
// Handle all other types of exceptions
}
}

The “finally” Clause

The last component of the “try…catch…finally” statement is the optional “finally” clause.  The “finally” clause is a block of code that is executed after the “try” and “catch” clauses, regardless of any errors(不管是否抛出异常).  The “finally” clause is useful for including clean up code (closing files, etc.) that needs to be executed no matter what.  Note that the “finally” clause is even executed if an exception occurs that is not caught.  In such a scenario, the “finally” clause is executed and then(如果没有catch,在这种情况下抛出的异常会在finally部分执行完之后才抛出) the thrown exception proceeds normally.

One interesting note about the “finally” clause is that it will be executed even if the “try” or “catch” clause executes a “return” statement.  For example, the following function returns false because the “finally” clause is the last thing to execute.

function foo() {
try {
return true;
} finally {
return false;
}
}

Throwing Exceptions

JavaScript allows programmers to throw their own exceptions via the appropriately named “throw” statement.  This concept can be somewhat confusing to inexperienced developers.  After all, developers strive to write code that is free of errors, yet the “throw” statement intentionally introduces them.  However, intentionally throwing exceptions can actually lead to code that is easier to debug and maintain(抛出异常相对js直接停下,会更容易调试和维护).  For example, by creating meaningful error messages it becomes easier to identify and resolve problems.

Several examples of the “throw” statement are shown below.  There is no restriction on the type of data that can be thrown as an exception.  There is also no limit on the number of times that the same data can be caught and thrown.  In other words, an exception can be thrown, caught, and then thrown again.

throw true;
throw 5;
throw "error message";
throw null;
throw undefined;
throw {};
throw new SyntaxError("useful error message");

While the “throw” statement can be used with any data type, there are certain benefits to using the built-in exception types.  Firefox, for example, gives special treatment to those objects by adding debugging information such as the filename and line number where the exception occurred.

As an example scenario, assume that a division operation occurs somewhere in your application.  Division can be a nuisance because of the possibility of division by zero.  In JavaScript, such an operation results in “NaN”.  This can lead to confusing results that are tricky to debug.  Things would be much simpler if the application complained loudly about the division by zero.  The following “if” statement accomplishes this for us by throwing an exception.

if (denominator === 0)
throw new Error("Attempted division by zero!");

Of course, it might be more appropriate to use a “RangeError” as shown below.

if (denominator === 0)
throw new RangeError("Attempted division by zero!");

JS Error 内置异常类型 处理异常 Throw语句的更多相关文章

  1. 【Go入门教程2】内置基础类型(Boolean、数值、字符串、错误类型),分组,iota枚举,array(数值),slice(切片),map(字典),make/new操作,零值

    这小节我们将要介绍如何定义变量.常量.Go内置类型以及Go程序设计中的一些技巧. 定义变量 Go语言里面定义变量有多种方式. 使用var关键字是Go最基本的定义变量方式,与C语言不同的是Go把变量类型 ...

  2. go - 内置基础类型

    Go 语言中包括以下内置基础类型: 布尔型:bool 整型:int int64 int32 int16 int8 uint8(byte) uint16 uint32 uint64 uint 浮点型:f ...

  3. js中内置有对象

    statpot:使用mongo+bootstrap+highcharts做统计报表 最近做了一个统计项目,这个统计项目大致的需求是统计接口的访问速度.客户端会调用一个接口来记录接口的访问情况,我的需求 ...

  4. 【Go入门教程4】变量(var),常量(const),内置基础类型(Boolean、数值 byte,int,rune、字符串、错误类型),分组,iota枚举,array(数值),slice(切片),map(字典),make/new操作,零值

    这小节我们将要介绍如何定义变量.常量.Go 内置类型以及 Go 程序设计中的一些技巧. 定义变量 Go 语言里面定义变量有多种方式. 使用 var 关键字是 Go 最基本的定义变量方式,与 C 语言不 ...

  5. go语言内置基础类型

    1.数值型(Number) 三种:整数型.浮点型和虚数型(有符号整数表示整数范围 -2n-1~2n-1-1:无符号整数表示整数范围 0~2n-1) go内置整型有:uint8, uint16, uin ...

  6. js arguments 内置对象

    1.arguments是js的内置对象. 2.在不确定对象是可以用来重载函数. 3.用法如下: function goTo() { var i=arguments.length; alert(i); ...

  7. 使用原生js自定义内置标签

    使用原生js自定义内置标签 效果图 代码 <!DOCTYPE html> <html lang="en"> <head> <meta ch ...

  8. js单体内置对象

    js单体内置对象:js的内置对象,是ECMAScritp提供的.不依赖于宿主环境的对象,我的理解就是在我们开发之前js里面就已经存在的对象.单体内置对象就是是不需要通过new来实例化的,例如我们的st ...

  9. C# 内置的类型转换方法

    C# 提供了下列内置的类型转换方法: 序号 方法 & 描述 1 ToBoolean把类型转换为布尔型. 2 ToByte把类型转换为字节类型. 3 ToChar如果可能的话,把类型转换为单个 ...

随机推荐

  1. Typecho V1.1反序列化导致代码执行分析

    0x00  前言     今天在Seebug的公众号看到了Typecho的一个前台getshell分析的文章,然后自己也想来学习一下.保持对行内的关注,了解最新的漏洞很重要. 0x01  什么是反序列 ...

  2. 蓝桥杯-Anagrams问题

     算法训练 Anagrams问题   时间限制:1.0s   内存限制:512.0MB      问题描述 Anagrams指的是具有如下特性的两个单词:在这两个单词当中,每一个英文字母(不区分大小写 ...

  3. Jenkins 源代码编译

    最近一直想写一个关于 Jenkins 管理的 InelliJ 插件,但是尝试很多次总是在登录认证上面失败,各种办法都不起作用,而且官方的文档含糊不清,就动起了从源代码编译在开发环境中进行调试. 废话少 ...

  4. setTimeOut函数和setInterval函数

    setTimeout( )是设定一个指定等候时间 (单位是千分之一秒, millisecond), 时间到了, 浏览器就会执行一个指定的 method 或 function, 有以下语法: 今次例子是 ...

  5. 关于clear与清除浮动

    今天看bootstrap突然看到了 .container:after { clear: both; } 好像对clear的用法有点模糊,于是于是又研究一下用法. 上面搜资料总会搜到张鑫旭老师的相关文章 ...

  6. https证书pfx 生成 pem,crt,key

    (1)将.pfx格式的证书转换为.pem文件格式:    openssl pkcs12 -in xxx.pfx -nodes -out server.pem (2)从.pem文件中导出私钥server ...

  7. RabbitMQ的安装和配置化可视界面

    RabbitMQ在windows下的安装 RabbitMQ 它依赖于Erlang,在window上安装时,需要先安装Erlang. 首先确定你的window电脑是32位还是64位,然后下载对应版本的E ...

  8. 原来你是这样的http2......

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由mariolu发表于云+社区专栏 序言 目前HTTP/2.0(简称h2)已经在广泛使用(截止2018年8月根据Alexa流行度排名的头 ...

  9. 吴恩达《深度学习》第二门课(3)超参数调试、Batch正则化和程序框架

    3.1调试处理 (1)不同超参数调试的优先级是不一样的,如下图中的一些超参数,首先最重要的应该是学习率α(红色圈出),然后是Momentum算法的β.隐藏层单元数.mini-batch size(黄色 ...

  10. 每天一道剑指offer-二叉树的下一个结点

    题目 每天一道剑指offer-二叉树的下一个结点 https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13& ...