0

Have a piece of logic that looks like that:

Dim fInfo As New FileInfo(LocationDir & Filename)
If Not fInfo.Exists Then
    Console.WriteLine("File does not exist." & Filename)
    Throw New Exception("File does not exist." & Filename)
End If

That supposed to throw the exception, stop the execution of the whole module, and get out. Understand it is not a peaceful ending. When I am getting is that there is unhandled error. and besides the console , another box pops up: that the application failed, and needs to be closed or debugged. I guess I need to handle the graceful termination of the module. Any suggestions?

Roland asked a great question where do I catch that user exception. And I am being totally honest that after searching and reading a lot, still cannot understand where and how I can catch it. It could be very trivial for experienced users, but would love to have a piece of code to use as a base.

user3235631
  • 79
  • 3
  • 14
  • Where do you catch the exception? – Rowland Shaw Feb 07 '14 at 21:34
  • And that is what I am trying to find out how to code efficiently to catch the exception.I know that I am currently not catching it – user3235631 Feb 07 '14 at 21:46
  • Meh, look for inefficient code first, easier to find. Exception handling is covered in any introductory book on VB.NET programming. Do note that the test is actually worthless, you have no guarantee that another process doesn't delete the file a microsecond later. This kind of code just doesn't work so just don't write it. Open the file, that will fail if it doesn't exist, you get the exception for free. – Hans Passant Feb 07 '14 at 22:19
  • thanks, found it. and the file does not get deleted. – user3235631 Feb 07 '14 at 22:30
  • Still have to ask, I understand there are lots of materials on exception handling, but unfortunately some people learn more and faster if they see real example. That is why I was trying to get help on how to handle different exceptions. For example, checking for file existence or being empty. And when the statement Throw is executed, wanted to see how not to cause the program not to crash, but rather finish in a peaceful manner. If there are any examples available, would be much appreciated. – user3235631 Feb 08 '14 at 21:15

1 Answers1

0

It is probably easier to use the IO.FileExists function and the IO.Path.Combine function to build the path.

If IO.File.Exists(IO.Path.Combine(LocationDir, Filename)) Then
   'code
End If

I at least never had a problem with it. Also like, Rowland wrote, you of course have to catch the exception you throw in your code somewhere if you forgot.

Jens
  • 6,275
  • 2
  • 25
  • 51