Skip to content
0x007e edited this page Oct 27, 2020 · 1 revision

How to use ExceptionLib

First it is necessary to create a new project:

dotnet new console -n MyApp

Open project with VisualStudio or VisualStudio Code or any other editor and in console switch to folder MyApp (cd MyApp) and install the exeption library:

dotnet add package RaGae.Exception

After adding the package add a new file with following content:

MyException.cs

using System;
using RaGae.ExceptionLib;

namespace MyApp
{
    // It is also possible to use a basic type or class for Type T instead of enums.
    public  enum ErrorCode
    {
        OK,
        ERROR,
        TEST
    }

    public class MyException : BaseException<ErrorCode>
    {
        public MyException() { }

        public MyException(string message) : base(message) { }

        public MyException(ErrorCode errorCode) : base(errorCode) { }

        public MyException(ErrorCode errorCode, string message) : base(errorCode, message) { }

        public override string ErrorMessage()
        {
            switch (base.ErrorCode)
            {
                case ErrorCode.OK:
                    return "TILT: Should not be reached";
                case ErrorCode.ERROR:
                    return $"Error: {base.Message}";    
                default:
                    return string.Empty;
            }
        }
    }
}

Now adapt the main program:

main.cs

using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.Write("Input: ");
            string read = Console.ReadLine();

            try
            {
                if(int.TryParse(read, out int number))
                {
                    Console.WriteLine(number);
                }
                else
                {
                    throw new MyException(ErrorCode.ERROR, "Input is not a number");
                }

                if(number < 0)
                    throw new Exception("Number should not be negative");
            }
            catch (MyException ex)
            {
                Console.WriteLine(ex.ErrorMessage());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

Run the Program:

dotnet run

Input: 10
10
Input: string
Error: Input is not a number
Input: -1
Number should not be negative
Clone this wiki locally