C# Exceptions

C# Code Snippets Exceptions
Share:

About

In this code snippet, we will learn about exceptions in C#.

When an error occurs in an application an exception will be thrown. If it’s left unhandled the application will crash. Exceptions also get thrown if you try to access a resource on your computer that is unavailable. For example, a file that doesn’t exist or is already opened by another program.

To prevent your application form crashing you must always implement exception handling with the try catch block when dealing with resources that you have no direct control over(files, networking, COM ports, …). 

When you write your own code you can also throw exceptions to indicate that an error has occurred. And if you need you can also make custom exceptions.

To create our own exception we simply create a class and make it inherit from the Exception class. Any custom properties and methods can be added to our new custom exception class. You then throw and handle the custom exception the same way you would any other exception. 

Let’s see how to handle, throw and make custom exceptions in the code example below.

Code:

using System;

namespace Exceptions
{
    class Program
    {
        static void Main(string[] args)
        {
            //Application crashes if exception is unhandled.
            //getException();
        
            try
            {
                //Code that can throw out exceptions should be wrapped with a try catch statement.
                //If not directly at least at a higher level to catch any potential exceptions to prevent the app from crashing.
                getException();
            }
            catch (MyCustomException ex)
            {
                //Catches specified type of exception in this case MyCustomException. 
                Console.WriteLine(ex.ErrorDescription);
            }
            catch (Exception ex)
            {   
                //Catches all type of exceptions.
                Console.WriteLine(ex.Message);
            }
            finally
            {
                //Finally always runs. 
                Console.WriteLine("This always gets executed.");
            }

            Console.ReadLine();
        }

        public static void getException()
        {
            throw new MyCustomException("Custom Exception Error.");
        }
    }

    class MyCustomException : Exception
    {
        //To create a custom exception we simply make a class and make it inherit from the Exception class.
        public string ErrorDescription { get; set; }
        public MyCustomException(string error)
        {
            ErrorDescription = error;
        }
    }
}

Result

What happens if the exception is left unhandled.
Handling the exception.
Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger