zoukankan      html  css  js  c++  java
  • js常识复记(2) -- 异常捕捉

    
    

     // 何时:如果函数的定义者,需要告知调用者使用过程中的错误;

     // 如何:throw new Error("提示文字");

    // 程序猿甲:定义函数的人
    function round(num, d){
        if(!isNaN(num) && !isNaN(d)){
            num *= Math.pow(10, d);
            return num;
        }else{
            // 抛出自定义错误
            throw new Error("参数必须是数字");  
        }
    }
    
    // 程序猿乙:调用函数的人
    var d = parseInt(prompt('请输入数字'));
    try{
        alert(round(123.456, d));
    }catch(err){
        alert(err.message);  // 接住抛出的自定义错误
    }
    //即使程序发生错误,也保证不异常中断的机制。
    try
    { 可能发生错误的代码 }catch(err){ 只有发生错误时才执行的代码 }finally{ 无论是否出错,肯定都要执行的代码 }
  • 相关阅读:
    36、【opencv入门】运动物体检测(2)
    二叉树数
    多边形的三角划分
    乘积最大
    加分二叉树
    c++ 装箱问题
    生物基元问题
    一般性的最少硬币组成问题
    打包
    挤牛奶
  • 原文地址:https://www.cnblogs.com/lanyueff/p/12170290.html
Copyright © 2011-2022 走看看