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; } } }