如何捕捉无支持图像 [英] How to catch none support image

查看:103
本文介绍了如何捕捉无支持图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在返回之前捕获无支持图像,但仍需要帮助。请



它没有抓到任何东西,让我的应用程序崩溃。



什么我试过了:



I want to catch None Support Image before return, but still need help. Please

It doesn't catch Anything, and make my app Crash.

What I have tried:

<pre lang="c#">
 public static ImageBrush GetImage(string source)
{
 if (System.IO.File.Exists(source))
            {
                ImageBrush myBrush = new ImageBrush();
                try
                {
                    myBrush.ImageSource = new BitmapImage(new Uri(source, UriKind.Relative));
                }
                catch
                {
                    myBrush.ImageSource = new BitmapImage(new Uri(Root.DefaultObjectPicture, UriKind.Relative));
                }

                return myBrush;

            }
}
// and caller method
try{
         MyRectangle.Fill = GetImage(@"BrokenImageTest.jpg");
}
catch{}

推荐答案

你不是在处理异常而是调用一个很可能抛出的函数你的 catch 处理程序中的另一个。



您应该阅读有关异常的内容:try-catch(C#Reference)| Microsoft Docs [ ^ ]。



然后通过读取函数引用并处理它们来检查所使用函数可能引发的异常。

对于你的情况:

BitmapImage构造函数(Uri)(System.Windows.Media.Imaging) [ ^ ]和

Uri构造函数(String,UriKind)(系统) [ ^ ]。



所以必须是类似

You are not handling exceptions but call instead a function that very probably throws another one in your catch handler.

You should read about exceptions: try-catch (C# Reference) | Microsoft Docs[^].

Then check which exceptions might be thrown by the used functions by reading the function references and handle them.
For your case:
BitmapImage Constructor (Uri) (System.Windows.Media.Imaging)[^] and
Uri Constructor (String, UriKind) (System)[^].

So it must be something like
bool bSuccess = false;
try
{
    // Call function(s) here that might throw exceptions

    // If execution reaches this point, no exceptions occured
    bSuccess = true;
}
// Catch and handle exceptions
catch (UriFormatException e)
{
    // Handle UriFormatException here
}
catch (FileNotFoundException e)
{
    // Handle FileNotFoundException here
}
// Handle more excpetions here as necessary

if (!bSuccess)
{
    // Try a different method which may throw also exceptions that should be handled
}


这篇关于如何捕捉无支持图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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