In a try...catch block, all of your code which might generate (throw) an exception if something goes wrong comes in the try block. The code in the try section executes by default. However, if there is some error underground and the exception is to be thrown, the try block is no longer executed and the catch block is executed further where you handle the error or show an error message.
If your code is supposed to run from line 1 to line x and there are some chances of getting a error. You can wrap the code (
from line 1 to line x) inside the try section. And add a catch block after it, to
catch the exception that thrown.
You code would look like this,
private void Decrypt_Click(object sender, RoutedEventArgs e)
{
try {
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == true)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
myStream.Close();
{
UnicodeEncoding ue = new UnicodeEncoding();
byte[] key = ue.GetBytes(Genkey.Text);
string cryptFile = saveFileDialog1.FileName;
using (FileStream fileCrypt = new FileStream(cryptFile, FileMode.Create))
{
using (AesManaged Decrypt = new AesManaged())
{
using (CryptoStream cs = new CryptoStream(fileCrypt, Decrypt.CreateDecryptor(key, key), CryptoStreamMode.Write))
{
using (FileStream fileInput = new FileStream(Openfile.Text, FileMode.Open))
{
Decrypt.KeySize = 256;
Decrypt.BlockSize = 128;
int data;
while ((data = fileInput.ReadByte()) != -1)
cs.WriteByte((byte)data);
}
}
}
}
MessageBox.Show("File Successfully Decrypted", "Decrypted!");
}
}
}
catch (Exception er) {
MessageBox.Show("Sorry, there was error. Error message: " + er.Message);
}
}
Try catch is widely used in all programming language to let you handle any unwanted case where your program might break. Read more about it on MSDN:
https://msdn.microsoft.com/en-us/library/0yd65esw.aspx[
^]