Click here to Skip to main content
16,013,338 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: (untagged)
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{}
Posted

1 solution

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
C#
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
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900