Try——catch的基本用法
const user={email:`jdoe@gmail.com`}
try{//执行代码
}catch(e){
//若try抛出错误,进入catch
}finally{
//不管try是否抛出错误,都进入此位置
}
//catch 可以不打断js的读取
console.log('Program continues');
ReferenceError
调用一个未定义的函数
try{
//Produce a ReferenceError
myFunction();
//自己抛出错误
if(!user.name){
// throw `User has no name`; //抛出string
throw new SyntaxError(`User has no name`);//抛出语法错误
}
}catch(e){// 一旦有错误就catch
console.log(e);//包括错误类型
console.log(e.message); //得到错误的内容
console.log(e.name); //得到错误类型
console.log(e instanceof ReferenceError); //true
console.log(e instanceof TypeError); //false
}finally{
//运行无论是否错误
console.log('Finally runs reguardless of result...');
}
Typeerror
对null调用methods
try{
//Produce a Typeerror
null.myFunction();
}
}catch(e){// 一旦有错误就catch
console.log(e);//包括错误类型
console.log(e.message); //得到错误的内容
console.log(e.name); //得到错误类型
console.log(e instanceof ReferenceError); //false
console.log(e instanceof TypeError); //true
}finally{
//运行无论是否错误
console.log('Finally runs reguardless of result...');
}
SyntaxError
对非公式类字符串使用eval;
try{
//will produce syntaxError
console.log(eval(`Hello world`)); //用于计算string的数字
}catch(e){// 一旦有错误就catch
console.log(e);//包括错误类型
console.log(e.message); //得到错误的内容
console.log(e.name); //得到错误类型
console.log(e instanceof ReferenceError);
console.log(e instanceof TypeError);
}finally{
//运行无论是否错误
console.log('Finally runs reguardless of result...');
}
URIError
try{
//will produce a URIError
decodeURIComponent(`%`);
}catch(e){// 一旦有错误就catch
console.log(e);//包括错误类型
console.log(e.message); //得到错误的内容
console.log(e.name); //得到错误类型
console.log(e instanceof ReferenceError);
console.log(e instanceof TypeError);
}finally{
//运行无论是否错误
console.log('Finally runs reguardless of result...');
}
自定义Error
const user={email:`jdoe@gmail.com`}
try{
//自己抛出错误
if(!user.name){
// throw `User has no name`; //抛出string
throw new SyntaxError(`User has no name`);//抛出语法错误
//传入的stirng为message
}
}catch(e){// 一旦有错误就catch
console.log(`User ERRor: ${e.message}`);
}finally{
//运行无论是否错误
console.log('Finally runs reguardless of result...');
}