Decryption Exception Problem

TedN

Active member
Joined
Sep 25, 2006
Messages
35
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:

Code:
   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
 
Statements outside Try block

Code:
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:
 
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
 
Back
Top