I'm quite new to the try catch and exception handling. I want my program to catch the exception when the directory or file is not found.
Whenever I run the program I get the error "DirectoryNotFoundException was unhandled by user code - An exception of type 'System.IO.DirectoryNotFoundException' occured in something.dll but was not handled in user code"
I can see that Visual Studio breaks at the DirectoryNotFoundDirection, any ideas?
try {
LiveDownloadOperation operation = await connectClient.CreateBackgroundDownloadAsync(filePath);
var result = await operation.StartAsync();
}
catch (FileNotFoundException filEx) {
Debug.WriteLine(filEx.Message);
throw filEx;
}
catch (DirectoryNotFoundException dirEx) {
Debug.WriteLine(dirEx.Message);
throw;
}
catch (IOException ioEx) {
Debug.WriteLine(ioEx.Message);
throw ioEx;
}
catch (Exception ex) {
Debug.WriteLine(ex.Message);
throw;
}
EDIT: to show code inside try
Because the directory does not exist (or has permissions problems, etc.), it throws an DirectoryNotFoundException.
Which you handle, then reraise -- because of the, the debugger rightly says that the exception is not handled.
Related
Hello guys i'm working on Database assignment in this i have one windows form and one class that i use to connect database and to execute queries and non-queries.
Question: I m using Post-Message label which inform only when "Product added successfully".but when i send wrong-data which can occur exception in executeNonQuery() in database class and after catching this exception and showing Error in message box.Control goes back to caller and it prints lblPostMsg in both cases which is "Product has been added successfully".
I want that when exception occur in database class i can stop executing rest of the code or if there is way that exception in calling method can be caught by caller method.
below is Code of windows Form button
private void btnInsert_Click(object sender, EventArgs e)
{
con = new DbConnection();
con.SqlQuery("INSERT INTO products VALUES(#products_ID,#products_Name)");
con.cmd.Parameters.AddWithValue("#products_ID", txtProID.Text);
con.cmd.Parameters.AddWithValue("#products_Name", txtProName.Text);
try
{
con.ExecuteNonQueryF();
this.categoriesTableAdapter1.Fill(this.purchasemasterDS.categories);
SystemSounds.Beep.Play();
lblPostMsg.Show();
lblPostMsg.Text = "Product has been added successfully";
}
catch (Exception ex)
{
throw;
}
finally
{
con.CloseCon();
}
}
This code is from dbclass
public void ExecuteNonQueryF()
{
try
{
_con.Open();
cmd.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
}
you are catching, handling, and suppressing the Exception in ExecuteNonQueryF:
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
}
Though this handles the Exception by showing the message, it causes the code to continue executing; the Exception won't be raised to the caller.
If you add throw after your MessageBox.Show is executed, the Exception will be raised to the caller and execution stops.
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
throw;
}
Another option is to completely remove that try-catch in ExecuteNonQueryF - letting the caller (your button onclick method) handle the Exception.
you need to throw an explicit exception in ExecuteNonQuery's catch block like
throw new Exception(ex)
and then in calle's catch block you need to write "return" to return from function. This will stop furter execution of function.
If you want the Exception will be raised to the caller and execution stops, then you must use throw at the last line of your catch block.
catch (System.Exception ex)
{
/*
write your desire code. then throw
*/
throw;
}
I'm currently working with some code that is used in client server communication.
I has a lot (around 50) of the following try-catch blocks
try
{
return GetLogFiles(date);
}
catch (TimeoutException ex)
{
this.GetLogger("GetAllLogs").Error("C is not answering!", ex);
}
catch (ConnectionInterruptedException ex)
{
this.GetLogger("GetAllLogs").Error("Connection interrupted", ex);
}
catch (ActionNotSupportedException ex)
{
this.GetLogger().Error("Software-version not comaptible!", ex);
throw new VersionNotCompatibleException();
}
catch (EndpointNotFoundException ex)
{
this.GetLogger().Error("Problem with network, connection to core is lost!", ex);
}
catch (CommunicationException ex)
{
this.GetLogger().Error("Not expected communication-exception was thrown:", ex);
}
This makes for a LOT of code that is more or less always the same.
Now I thought about refactoring all the catch blocks into a method and just call it. Like
try
{
return GetLogFiles(date);
}
catch(Exception ex)
{
ExceptionHandling(string operation, Exception ex)
}
private void ExceptionHandling(string operation, Exception ex)
{
if (ex is TimeoutException)
{
this.GetLogger(operation).Error("C is not answering!", ex);
}
else if (ex is ConnectionInterruptedException)
{
this.GetLogger(operation).Error("Connection interrupted", ex);
}
else if (ex is CommunicationObjectFaultedException)
{
this.GetLogger(operation).Error("Core is not answering!", ex);
}
else if (ex is FaultException)
{
this.GetLogger(operation).Error("C is not answering!", ex);
}
else if (ex is ActionNotSupportedException)
{
this.GetLogger().Error("Software-version not comaptible!", ex);
throw new VersionNotCompatibleException();
}
else if (ex is EndpointNotFoundException)
{
this.GetLogger().Error("Problem with network, connection is lost!", ex);
}
else if (ex is CommunicationException)
{
this.GetLogger().Error("Not expected communication-exception was thrown:", ex);
}
else
{
this.GetLogger().Error("Unknown exception was thrown:", ex);
throw new Exception("Unknown exception occured during request handling", ex);
}
}
None of the codeparts does any ordinary handling in case of an exception, i.e. they get logged and that's it.
What problems do you see with extracting the exception part into its own method?
The main problem I see is that you're rethrowing the exception if it isn't one you expect, making you lose the real stack trace, plus using Exception in your catch is a very broad thing to do.
Lines of code isn't the real issue, and yes making things DRY is a good thing to do but its more likely that the thing that needs making dry is the GetLogFiles function to include the error handling inside of that, not the exception handler.
it's better to do that like this:
public class MyException : Exception
{
public MyException(Exception ex)
{
// handle exception
}
}
and
try
{
}
catch(Exception ex)
{
throw new MyException(ex)
}
I am writing a C# application in which I have to display a message if File is already being used by some process and if the file doesnot exist, the application needs to display another message.
Something like this:
try
{
//Code to open a file
}
catch (Exception e)
{
if (e IS IOException)
{
//if File is being used by another process
MessageBox.Show("Another user is already using this file.");
//if File doesnot exist
MessageBox.Show("Documents older than 90 days are not allowed.");
}
}
Since IOException covers both the conditions, how do I distinguish if this exception is caught because of File being used by another process or File doesnot exist?
Any help would be highly appreciated.
Always catch from the most specific to the most generic exception type.
Every exception inherits the Exception-class, thus you will catch any exception in your catch (Exception) statement.
This will filter IOExceptions and every else separately:
catch (IOException ioEx)
{
HandleIOException(ioEx);
}
catch (Exception ex)
{
HandleGenericException(ex);
}
So catch Exception always last. Checking with if is possible, but not common.
About your problem:
if (File.Exists(filePath)) // File still exists, so obviously blocked by another process
This would be the simplest solution to separate your conditions.
As you can see here File.OpenRead can throw these exception type
ArgumentException
ArgumentNullException
PathTooLongException
DirectoryNotFoundException
UnauthorizedAccessException
FileNotFoundException
NotSupportedException
for each of this exception type you can handle it in this way
try{
}
catch(ArgumentException e){
MessageBox.Show("ArgumentException ");
}
catch(ArgumentNullExceptione e){
MessageBox.Show("ArgumentNullExceptione");
}
.
.
.
.
catch(Exceptione e){
MessageBox.Show("Generic");
}
In your case you can handle just one or two types and other are always catched by generic Exception (it must be always the lastone because cathces all Exceptions)
Try the following:
try
{
//open file
}
catch (FileNotFoundException)
{
MessageBox.Show("Documents older than 90 days are not allowed.");
}
catch (IOException)
{
MessageBox.Show("Another user is already using this file.");
}
More info: http://www.dotnetperls.com/ioexception
I know this is old, but the only consistent solution to do this is to filter catch blocks by the HResult property. I don't know which one it is but here's an example for copying a file and catching if the file already exists :
try
{
File.Copy(source, dest, false); // Try to copy the file normally
}
catch (IOException e) when (e.HResult == -2147024816) // 0x80070050 : The file already exists
{
// Prompt user for overwrite...
}
Consult the .NET reference source and track the Win32 calls to find the returned HResult.
When file not exists it will throw the FileNotFoundException that inherit IOException, So you can write like this:
try
{
//file operate
}
catch (FileNotFoundException ex)
{
MessageBox.Show("Documents older than 90 days are not allowed.");
}
catch (IOException ex)
{
MessageBox.Show("Another user is already using this file.");
}
I have to process items off a queue.
Deleting items off the queue is a manual call to Queue.DeleteMessage. This needs to occurs regardless of whether or not the processing succeeds.
var queueMessage = Queue.GetMessage();
try
{
pipeline.Process(queueMessage);
}
catch (Exception ex)
{
try
{
Logger.LogException(ex);
}
catch { }
}
finally
{
Queue.DeleteMessage(queueMessage);
}
Problem:
On failure, I log the error to some data store. If this logging fails (perhaps the data store is not available), I still need the message to be deleted from the queue.
I have wrapped the LogException call in another try catch. Is this the correct way or performing thing?
Following code is enough. finally blocks execute even when exception is thrown in catch block.
var queueMessage = Queue.GetMessage();
try
{
pipeline.Process(queueMessage);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
finally
{
Queue.DeleteMessage(queueMessage);//Will be executed for sure*
}
The finally block always executes, even if it throws an unhandled error (unless it end the app). So yes.
I'm using TweetSharp to find the followers for a user.
Here is the code:
public static void FindFollowersForUser(TwitterUserModel twitterUser)
{
try
{
var followers = service.ListFollowersOf(twitterUser.TwitterName, -1);
if (followers == null) return;
while (followers.NextCursor != null)
{
var foundFollowers = service.ListFollowersOf(twitterUser.TwitterName, (long)followers.NextCursor);
if (foundFollowers == null) continue;
Debug.WriteLine("Followers found for: " + twitterUser.TwitterName);
foreach (var follower in foundFollowers)
{
twitterUser.Followers.Add(follower.ScreenName);
}
}
}
catch (WebException e)
{
throw e;
}
}
I've tried wrapping the code in a try/catch, to catch the WebException error being fired and review it's InnerException, but the catch is never entered despite the error message being shown in the output window (View -> Output) in Visual Studio.
How can I see the inner exception of this breaking bug? This is the first time I've seen the debugger not firing the catch when an exception is fired.
I assume when you say "First chance exception" you mean the message that is output to the Debug console? That message is output whenever an exception is thrown. The exception may be caught by code and handled and not allowed to propagate up the stack. TweetSharp may be catching this exception within its code and handling in some way so it never reaches your catch block
This is normal and only the debugger displays this message. If this is a problem for you in some way (other than the message displaying in the Output window), please provide more detail.
I was looking something else, really, but this cought my eye. If you are planning to rethrow exception then you want to replace this
catch (WebException e) { throw e; }
with this so you won't mess up the stacktrace.
catch (WebException e) { throw; }