Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I am accessing data from an encrypted file, decrypting it then placing it in an arraylist. Exceptions would normally occur if an incorrect password is entered when opening the program. The password is used to provide keys for the encryption/decryption process.

 

If any exceptions occur in the decrypting process I would like to return the program back to a password entry panel.

 

My problem is that the Try-Catch process still allows a system error to occur when an incorrect password is entered and then the program terminates.

 

It would seem I need to add a specific exception(s) to the Catch line. But how does one know what exceptions to place there, e.g.

 

Catch ex As System.Exception When Not .......................

 

The decryption function is as follows:

 

  Public Function Decrypt() As Integer

       Dim fsRead As New FileStream(fileName, FileMode.Open, FileAccess.Read)
       Dim encStream As New CryptoStream(fsRead, key.CreateDecryptor(), CryptoStreamMode.Read)
       Dim sr As New StreamReader(encStream)
       Dim fileItem As String

       Try
           Do While sr.Peek <> -1
               fileItem = sr.ReadLine
               alData.Add(fileItem)
           Loop
           Decrypt = 1
       Catch ex As System.Exception
           MsgBox(ex.Message)
           Decrypt = 0
       End Try

       sr.Close()
       encStream.Close()
       fsRead.Close()

   End Function

 

 

Appreciate any help.

 

Thanks,

Ted

Posted

Statements outside Try block

 

Catch ex As System.Exception

 

The above statement will catch all non-fatal exceptions. Have you considered that exceptions might be thrown in the code before the Try block? Opening a file and opening a stream both have the potential to throw exceptions. If you place these statements within the Try block any exceptions they throw can be handled.

 

Also, I would recommend you put the final three statements of the function into a Finally block so that they will be executed whether an exception is thrown or not.

 

Good luck :cool:

Never trouble another for what you can do for yourself.
Posted

Thanks Paul. That helped a lot. One change I had to make was to put the final three statements in the Try block instead of the Finally block. It seems the original problem was caused by these statements still trying to close things when an exception had prevented opening.

Everything looks good now.

 

Thanks again.

Ted

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...