Reputation: 6492
Here is a code which I have written
if(Condition)
{
try
{
System.Diagnostics.Process.Start(Path) ;
}
catch ( Win32Exception Error)
{
MessageBox.Show(Error.Message) ;
}
}
Now, when I provided invalid input to
Path
ie a file that does not exist, instead of throwing the Win32 exception, my application is throwing
TargetInvocationError
How can I correct this ? ![enter image description here][1] Here is the stack trace
I then tried adding the lines
catch(FileNotFoundException Error)
{
MessageBox.Show(Error.Message) ;
}
but still the TargetInvocationException
is being thrown.
Upvotes: 0
Views: 229
Reputation: 17156
Either you catch the TargetInvocationException
or you catch an exception higher up in the hierarchy, like the base class Exception
.
Like this:
try
{
System.Diagnostics.Process.Start(Path) ;
}
catch ( Exception ex)
{
MessageBox.Show(ex.Message) ;
}
The other options is to catch both
try
{
System.Diagnostics.Process.Start(Path) ;
}
catch ( TargetInvocationException ex)
{
MessageBox.Show(ex.Message) ;
}
catch ( Win32Exception ex )
{
MessageBox.Show(ex.Message) ;
}
However, "programming with exceptions" is not recommended (that is, using exceptions as part of your application flow). Instead make sure that Path
is valid before you try to use it. Providing an informative message that the path is incorrect instead of giving your users some cryptic message.
Upvotes: 1