简体   繁体   English

尝试捕获异常错误

[英]Try Catch Exceptions Error

When I use try catch exception with this piece of code, I get the following error: 当我在这段代码中使用try catch exception时,出现以下错误:

"not all code paths return values" “并非所有代码路径都返回值”

My code: 我的代码:

   public System.Drawing.Image Scan()
    {
        try
        {

           const string formatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
            WIA.CommonDialog scanDialog = new WIA.CommonDialog();
            WIA.ImageFile imageFile = null;
            imageFile = scanDialog.ShowAcquireImage(WIA.WiaDeviceType.ScannerDeviceType, WIA.WiaImageIntent.GrayscaleIntent,

            WIA.WiaImageBias.MinimizeSize, formatJPEG, false, true, false);
            WIA.Vector vector = imageFile.FileData;
            System.Drawing.Image i = System.Drawing.Image.FromStream(new System.IO.MemoryStream((byte[])vector.get_BinaryData()));

            return i;

        }
        catch (COMException ce)
        {
            if ((uint)ce.ErrorCode == 0x800A03EC)
            {
               return ce;

            }
        }

Change your catch block like below will work but still you face some issue. 像下面那样更改您的catch块将起作用,但是仍然遇到一些问题。 Because your method returns type Image and you are returning COMException in catch block. 因为您的方法返回类型Image并且您在catch块中返回COMException I suggest you to throw the exception or Log in catch block 我建议您抛出异常或登录catch块

if ((uint)ce.ErrorCode == 0x800A03EC)
{
    //DO LOGGING;
}
else
{
    throw ce;
}

You have two different problems here. 您在这里有两个不同的问题。 First, your catch block won't return anything if the condition is not met. 首先,如果不满足条件,您的catch块将不会返回任何内容。 Second, the return type within the catch block is not the same as the one inside of the try block. 其次,catch块内的返回类型与try块内的返回类型不同。

You probably want something more like this in your catch block: 您可能希望在catch块中添加更多类似的内容:

catch (COMException ce)
{
    if ((uint)ce.ErrorCode == 0x800A03EC)
        return null;  // Don't return anything if a specific code was found

    throw ce;         // Rethrow the exception for all other issues.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM