积极答复者
try catch 无法忽略异常

问题
答案
-
你好,我模拟了你的过程,我得出的结果是能得到异常的下面的我的代码:
XAML:
CS:<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="600" Width="900" Loaded="Window_Loaded"> <Border Name="border"/> </Window>
private void Window_Loaded(object sender, RoutedEventArgs e) { try { File.WriteAllText(@"C:\1.txt", "123"); var ib = new ImageBrush(); var uri = new Uri(@"C:\1.txt", UriKind.Absolute); var img = new BitmapImage(uri); border.Background = new ImageBrush(img); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
知识改变命运,奋斗成就人生!- 已标记为答案 buhuang 2011年9月2日 10:00
全部回复
-
你好!
按照你的提示,我并未发现上述问题。我的测试结果是若加载非图片类型的文件上述代码会自动忽略且不产生异常。
知识改变命运,奋斗成就人生!谢谢肖,
怪我马虎,你说的对。
我少贴了一行代码(粗斜体处)
ImageBrush ib_1 = new ImageBrush();if (File.Exists(ls_bg)){Uri uri_1 = new Uri("images\\sbg.jpg", UriKind.Relative);try{ib_1.ImageSource = new BitmapImage(uri_1);border_bg.Background = ib_1;}catch{}}经测试,问题也就出在这一行上。border_bg是一个Border控件,用vs调试时,会提示“未找到适用于完成此操作的图像处理组件”。但 try语句却无法捕获此异常,程序运行到这就自动退出了。
-
你好,我模拟了你的过程,我得出的结果是能得到异常的下面的我的代码:
XAML:
CS:<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="600" Width="900" Loaded="Window_Loaded"> <Border Name="border"/> </Window>
private void Window_Loaded(object sender, RoutedEventArgs e) { try { File.WriteAllText(@"C:\1.txt", "123"); var ib = new ImageBrush(); var uri = new Uri(@"C:\1.txt", UriKind.Absolute); var img = new BitmapImage(uri); border.Background = new ImageBrush(img); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
知识改变命运,奋斗成就人生!- 已标记为答案 buhuang 2011年9月2日 10:00
-
Uri uri_1 = new Uri("images\\sbg.jpg", UriKind.Relative);
有问题,关于Uri path如何书写, 你可以参考:
http://msdn.microsoft.com/zh-cn/library/aa970069.aspx
(关于绝对的Uri,也可以参考肖小勇的Uri)
Sheldon _Xiao[MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-
Uri uri_1 = new Uri("images\\sbg.jpg", UriKind.Relative);
有问题,关于Uri path如何书写, 你可以参考:
http://msdn.microsoft.com/zh-cn/library/aa970069.aspx
(关于绝对的Uri,也可以参考肖小勇的Uri)
Sheldon _Xiao[MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
谢谢sheldon,
问题不是来自于uri。
问题来自于border_bg.Background = ib_1
如果文件是一个图片,是正常的。若试图把background设置成指向非图片文件的imagebrush时,程序就会自动退出了,捕捉不到异常。但VS调试时会提示“未找到适用于完成此操作的图像处理组件”。