Try-Catch Block In Function [英] Try-Catch Block In Function

查看:96
本文介绍了Try-Catch Block In Function的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    function checkimgexist(){
try{
        document.getElementById('sample').src = 'res/defult/arrow.svg';
        }
   }
   catch(ex){
        cosole.log('error here is '+ex);
   }



如果图像存在,此代码有效,如果没有,则在控制台中显示错误。

我不确定是否这是异常,因为它看起来不像catch块的异常!


This code works if image exists and if not, it shows error in console.
I'm not sure whether it is this exception because it don't looks like exception of the catch block!

推荐答案

不,这不正确!你需要在你的函数中使用一个catch块:





No, this is not correct! You need a catch block IN your function like this:


function checkimgexist()
    {
        try
        {
           document.getElementById('sample').src = 'res/defult/arrow.svg';
        }
        catch(ex)
        {
          cosole.log('error here is '+ex);
        }
    }


确保图片标签随您的名字一起提供(样品)。

Make Sure the image tag is available with your name(Sample).
<img id="sample" src="" />



然后尝试访问您的代码


then try to access as your code

document.getElementById("sample").src





Javascript Try块只能在HTML文档中找到错误,而不是关于物理路径你的文件(res / defult / arrow.svg)。



对于exp,上面的代码就好像图像标签可用,然后用 res / defult / arrow.svg 设置图像标签的来源b>

否则它会将错误抛给Catch Block。



The Javascript Try block can only find error with in the HTML document, not about the Physical Path of your file(res/defult/arrow.svg).

For exp, above code works as if the image tag is available then sets source of the image tag with "res/defult/arrow.svg"
other wise it throws the error to Catch Block.


代码格式化不正确。只需检查关闭括号。
Code formatting is not correct. Just check the closing braces.


这篇关于Try-Catch Block In Function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆