Handling Exceptions With Try/Catch/Finally

OpenDialogCd

OpenDialogMainForm

It is inevitable at some point in coding that you will come across the need to handle errors and exceptions. You can take care of most predictable scenarios but checking variables and such. However users will always find ways to work with your programs in ways you never intended or saw coming. And in doing this they will introduce errors that you will need to handle. That’s where try/catch/finally comes into play. I made a simple text file reader to demonstrate the ability to throw custom errors based off the ReadAllText() method. This gives a small glimpse into catching and handling exceptions.


MainForm Class


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Security;
using System.Windows.Forms;

namespace OpenDialog
{
    public partial class MainForm : Form
    {
        //Private class variables and objects.
        private OpenTheFile _openTheFile = new OpenTheFile();

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            //If the exit menu item is selected.
            exitToolStripMenuItem.Click += (from, ea) => this.Close();

            //If the open menu item is selected.
            openToolStripMenuItem.Click += (from, ea) =>
                {
                    //Calling the method to perform the tasks of opening the file, getting the name, getting the contents, 
                    //and getting the file size.
                    _openTheFile.OpenFile();

                    //Displaying the file in the main window.
                    mainRichTextBox.Text = _openTheFile.ReadText;

                    //Displaying the file name and size information.
                    DisplayFileInfo("File Name: " + _openTheFile.FileName, "File Size: " + _openTheFile.FileSize.ToString());
                };

            //If the clear menu item is selected.
            clearToolStripMenuItem.Click += (from, ea) =>
                {
                    //Clearing the main window.
                    mainRichTextBox.Clear();

                    //Resetting the file name and size info area.
                    DisplayFileInfo();
                };

            //Using a foreach loop to create event handlers for all of the Exception submenu items.
            foreach (ToolStripMenuItem items in exceptionsToolStripMenuItem.DropDownItems)
            {
                //Putting a checkmark next to the none option as a default.
                noneToolStripMenuItem.Checked = true;

                //Creating event handlers for all of the submenu items.
                items.Click += new EventHandler(exceptionsToolStripMenuItem_Click);
            }
        }

        private void exceptionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
            if (menuItem != null)
            {
                //Unchecking all of the subitems.
                foreach (ToolStripMenuItem items in exceptionsToolStripMenuItem.DropDownItems)
                    items.Checked = false;

                //Putting a checkmark on the clicked subitem.
                menuItem.Checked = true;

                //Calling on the throwing exceptions method.
                _openTheFile.ThrowingExceptions(menuItem.Text);
            }
        }

        //Method with default parameters used to control the filename and filesize display at the bottom of the user screen.
        private void DisplayFileInfo(string fileName = "File Name:", string fileSize = "File Size:")
        {
            fileNameStatusLabel.Text = fileName;
            fileSizeStatusLabel.Text = fileSize;
        }
    }
}

 

OpenTheFile Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security;
using System.Windows.Forms;

namespace OpenDialog
{
    class OpenTheFile
    {
        //Private class variables.
        private string _filePath = Application.StartupPath + @"\files\";
        private string _file;
        private string _readText;
        private string _fileName;
        private int _fileSize;

        //Public properties.
        public string FilePath { get { return _filePath; } }
        public string ReadText { get { return _readText; } }
        public string FileName { get { return _fileName; } }
        public int FileSize { get { return _fileSize; } }

        //Method for when a text file is requested to be opened.
        public void OpenFile()
        {
            //Showing an open file dialog at the file location.
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.InitialDirectory = _filePath;
            fileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            fileDialog.FilterIndex = 1;
            DialogResult fileResult = fileDialog.ShowDialog();

            //Getting the text data from the file.
            _file = fileDialog.FileName;

            if (fileResult == DialogResult.OK)
            {
                //Try/Catch/Finally block for all the Exceptions in the ReadAllText() method. 
                try
                {
                    _readText = File.ReadAllText(_file);
                }
                catch (ArgumentException ex)
                {
                    ExceptionInfo(ex);
                }
                catch (PathTooLongException ex)
                {
                    ExceptionInfo(ex);
                }
                catch (DirectoryNotFoundException ex)
                {
                    ExceptionInfo(ex);
                }
                catch (IOException ex)
                {
                    ExceptionInfo(ex);
                }
                catch (UnauthorizedAccessException ex)
                {
                    ExceptionInfo(ex);
                }
                catch (NotSupportedException ex)
                {
                    ExceptionInfo(ex);
                }
                catch (SecurityException ex)
                {
                    ExceptionInfo(ex);
                }
                catch (Exception ex)
                {
                    ExceptionInfo(ex);
                }
                finally
                {
                    _fileName = Path.GetFileName(_file);
                    _fileSize = _readText.Length;
                }
            }
        }

        //Displaying the caught exception info.
        private void ExceptionInfo(Exception exceptionName)
        {
            MessageBox.Show(exceptionName.Message, "Application Error", MessageBoxButtons.OK);
            Console.WriteLine(exceptionName.StackTrace);
        }

        //method used for throwing exceptions.
        public void ThrowingExceptions(string exceptionName)
        {
            //Using a Try/Catch block for all of the custom exceptions.
            try
            {
                if (exceptionName == "ArguementException")
                    throw new ArgumentException();
                if (exceptionName == "PathTooLongException")
                    throw new PathTooLongException();
                if (exceptionName == "DirectoryNotFoundException")
                    throw new DirectoryNotFoundException();
                if (exceptionName == "IOException")
                    throw new IOException();
                if (exceptionName == "UnauthorizedAccessException")
                    throw new UnauthorizedAccessException();
                if (exceptionName == "FileNotFoundException")
                    throw new FileNotFoundException();
                if (exceptionName == "NotSupportedException")
                    throw new NotSupportedException();
                if (exceptionName == "SecurityException")
                    throw new SecurityException();
            }
            catch (ArgumentException ex)
            {
                //Displaying the exception info in a popup box and writing to the logfile.
                ExceptionInfo(ex);
                WriteToLog(ex);
            }
            catch (PathTooLongException ex)
            {
                ExceptionInfo(ex);
                WriteToLog(ex);
            }
            catch (DirectoryNotFoundException ex)
            {
                ExceptionInfo(ex);
                WriteToLog(ex);
            }
            catch (IOException ex)
            {
                ExceptionInfo(ex);
                WriteToLog(ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                ExceptionInfo(ex);
                WriteToLog(ex);
            }
            catch (NotSupportedException ex)
            {
                ExceptionInfo(ex);
                WriteToLog(ex);
            }
            catch (SecurityException ex)
            {
                ExceptionInfo(ex);
                WriteToLog(ex);
            }
        }

        //Method used to write data to log file(s).
        private void WriteToLog(Exception exception)
        {
            //Getting the error log path & filename.
            string errorLog = _filePath + @"errorlog.txt";

            //Date & Time stamp for the error log entry.
            DateTime now = DateTime.Now;

            //Building the string for the log file entry.
            StringBuilder errorLogUpdate = new StringBuilder();
            errorLogUpdate.AppendLine(now.ToString());
            errorLogUpdate.AppendLine(exception.GetType().FullName);
            errorLogUpdate.AppendLine(exception.Message).AppendLine(exception.StackTrace).AppendLine("");

            //Writing the data to the log file. 
            using (StreamWriter logUpdate = new StreamWriter(File.Open(errorLog, FileMode.Append)))
                logUpdate.Write(errorLogUpdate);
        }
    }
}

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s