Skip to content

JS之try-catch

  1. 支持 条件catch , 但是这个不是标准的用法,不要再生产环境使用
js
// 支持条件catch , 但是这个不是标准的用法,不要再生产环境使用
try {
    myroutine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
    // statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
    // statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
    // statements to handle EvalError exceptions
} catch (e) {
    // statements to handle any unspecified exceptions
    logMyErrors(e); // pass exception object to error handler
}

// 正确的方式是使用这个
try {
  myRoutine();
} catch (e) {
  if (e instanceof RangeError) {
    // statements to handle this very common expected error
  } else {
    throw e;  // re-throw the error unchanged
  }
}
// 支持条件catch , 但是这个不是标准的用法,不要再生产环境使用
try {
    myroutine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
    // statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
    // statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
    // statements to handle EvalError exceptions
} catch (e) {
    // statements to handle any unspecified exceptions
    logMyErrors(e); // pass exception object to error handler
}

// 正确的方式是使用这个
try {
  myRoutine();
} catch (e) {
  if (e instanceof RangeError) {
    // statements to handle this very common expected error
  } else {
    throw e;  // re-throw the error unchanged
  }
}
  1. 从 finally 语句块返回

try catch 代码块中是可以直接返回的,但是需要注意finally的情况。

js
function tryTest () {  
  try {  
    try {  
      // 不管return 或者 throw,都会得到abc  
      //return 'xx'      throw new Error("my error");  
    } catch (ex) {  
      console.error("catch", ex.message);  
      throw ex;  
    } finally {  
      console.log("finally");  
      return 'abc';  
    }  
  } catch (ex) {  
    console.error("outer", ex.message);  
  }  
}  
  
function clicked () {  
  console.log(tryTest())  
  // Output:  
  // finally 
  // abc
}
function tryTest () {  
  try {  
    try {  
      // 不管return 或者 throw,都会得到abc  
      //return 'xx'      throw new Error("my error");  
    } catch (ex) {  
      console.error("catch", ex.message);  
      throw ex;  
    } finally {  
      console.log("finally");  
      return 'abc';  
    }  
  } catch (ex) {  
    console.error("outer", ex.message);  
  }  
}  
  
function clicked () {  
  console.log(tryTest())  
  // Output:  
  // finally 
  // abc
}