views:

52

answers:

2

The requirement: On an error (thrown exception), the file being processed should be moved to the folder for files with errors (app.config setting).

The problem: The only way that I can of handling this is to have a nested Try/Catch inside of the main Try/Catch to try to move the file, that way if the move fails, another exception is thrown. I know that I can do my best to make sure the directory exists, rights are given, but since it is a network drive... I just know an error is bound to happen at some point.

Example

Try
   (Do Some Logic, but an error happens)
Catch ex As Exception
   Try
       (Attempt to move file)
   Catch exinner as Exception
       Throw New Exception("Cannot move file to Error Directory", innerex)
   End Try
   (Raise Error Event for logging by form/batch app)
End Try

Actually that came out even more horrible than what I was thinking it would look like.

Now I know I am doing something wrong. How should I really be trying to handle a possible error occuring in the catch, so that I can still move files and try to call my event?

+2  A: 

That all looks good to me. It is perfectly reasonable to have try catch blocks inside a catch. You can check all the things you mentioned but there is always the possibility that the network will go down or you just plain won't be able to write that file. What you do after that is up to you. An error message and pausing processing seems reasonable.

stimms
Fair enough. Thanks, it just seemed wrong to do it that way, but explains why I could not think of something better.
IPX Ares
+1  A: 

That is exactly how you'd do it when using Exceptions only. You might consider using flags, but that isn't better either:

(Set file processing error flag to false)
Try
   (Do Some Logic, but an error happens)
Catch ex As Exception
   (Set file processing error flag to true)
End Try

IF (file processing error flag = true)
   Try
       (Attempt to move file)
   Catch exinner as Exception
       Throw New Exception("Cannot move file to Error Directory", innerex)
   End Try
   (Raise Error Event for logging by form/batch app)
End Try

Not that much better...

Thorsten Dittmar
I would say that is less clean.
stimms
Of course it is, that's why I said the nested Exceptions approach was exactly how you'd do it right.
Thorsten Dittmar