关键字
throw:抛出一个自定义错误信息。
try:在执行时进行错误测试的代码块。
catch:当 try 代码块发生错误时,所执行的代码块。
finally:在 try 和 catch 之后无论有无异常都会执行。
1.try…catch
举例1
try {
console.log(num);
} catch (e) {
console.log(e);} finally {
console.log(‘不管是否出错,这里的代码都会执行。’);
}
console.log(‘能执行这行代码吗?’);
因为 try 里面的代码出现了错误,所以执行了 catch 里面的代码。之后又执行了 finally 里面的代码,因为 finally 里写的代码是不管 try 里的代码运行是否出错都会执行的。
举例2
function abc(){
console.log(“123”);
}
try{
cba();
}catch(e){
console.log([e])
console.log(e.message);
console.log(e.stack)
}
运行结果
try:必填
catch:选填
finally:选填
注意:catch 和 finally 都是可以选填。但在使用 try 语句时,catch 和 finally 必须使用其中一个跟着 try 后面。
以上就是普通异常处理的使用方法
2.throw
function children() {
throw new Error(“子报错”);
}
function parent() {
children(); //有异常抛出 函数中断执行
}
parent();
console.log(“cccccccc”);
运行结果
配合 throw 使用
举例1
function devide(a, b) {
if(0 === b) { // 分母为0
// 抛出异常
throw ‘分母不能为零!’;
}
return a/b;
} try {
// 可能会出现错误的代码
console.log(devide(10, 0));
} catch(e) {
// 出现错误后,会抛出自定义的错误
console.error(e);
}
举例2
function children() {
throw new Error(“子报错”);//Error要大写
}
function parent() {
//可以在上一层函数捕获下层函数的异常
try {
children();
} catch(error) {
console.log(error);
}
}
parent();
console.log(“cccccccc”);
/*
throw new Error(error); 这个是创建错误,创造一个错误类型抛出
throw error 这个是抛出错误。
*/
throw error 与 throw new Error(error)区别
throw new Error(error)
throw error
案例
提交电话
二、xml初识
- xml文件是用来做什么的
核心思想:
答:存储数据
延伸问题: xml是怎样存储数据的?
答:以标签的形式存储
例: coco
- 什么是xml元素? 元素该如何编写?
xml中的元素其实就是一个个的标签
标签分为两种, 包含标签体和不包含标签体
包含标签体
coco
18
不包含标签体
- 标签(元素的书写规范)
-
严格区分大小写;
<p><P>
-
只能以字母或下划线开头;abc _abc
-
不能以xml(或XML、Xml等)开头----W3C保留日后使用;
-
名称字符之间不能有空格或制表符;
-
名称字符之间不能使用冒号 : (有特殊用途)
-
元素中属性的注意事项
-
一个元素可以有多个属性,每个属性都有它自己的名称和取值。
-
属性值一定要用引号(单引号或双引号)引起来。
-
属性名称的命名规范与元素的命名规范相同
-
元素中的属性是不允许重复的
-
在XML技术中,标签属性所代表的信息也可以被改成用子元素的形式来描述
coco
18
- XML的注释
<!—被注释的内容 – >
- xml中常用转义字符(与html中类似)
| 特殊字符 | 替代字符 |
| — | — |
| & | & |
| < | < |
| > | > |
| " | " |
| ’ | ' |
coco
<itheima>www.baidu.com</itheima>
- xml中空格会被保留
html中会把多个连续的空格字符剪裁合并为一个
xml文本中空格不会被删节
运行结果