Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net how to detect if built-in exception is thrown manually via code in executing assembly

Tags:

c#

.net

.net-core

In my code there are lot of areas where we manually "throw" InvalidOperationException. We have specifc handlers for handling this exception type. However there is a requirement that we have to write some logic based on the fact if the exception came beacuse of a throw or it came from the system. Below is the example:

 static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Hello World!");
                //throwFirstLayer(); //if i uncomment this i am throwing the error manually
                var people = new List<Person>();

                people.Add(new Person("John", "Doe"));
                people.Add(new Person("Jane", "Doe"));
                people.Sort(); //Suppose in this line system throws InvalidOp exception
                foreach (var person in people)
                    Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
            }
            
            catch(InvalidOperationException ioex)
            {
                var e = ioex;
            }
}

public static void throwFirstLayer()
        {
            throw new InvalidOperationException("manual");
        }

 public class Person
    {
        public Person(String fName, String lName)
        {
            FirstName = fName;
            LastName = lName;
        }

        public String FirstName { get; set; }
        public String LastName { get; set; }
    }

here inside the catch block i want to detect if the exception had been thrown by me manually from the code or the system raised it due to an actual invalid operation?

like image 656
RyanDotnet Avatar asked Jan 25 '23 07:01

RyanDotnet


1 Answers

You could examine the stack trace of the exception and see where it originated from - but that's slow, and error-prone in production due to JIT optimizations.

I would question the wisdom of a design that needs this in the first place, but if you really, really, really need to do so, I'd suggest creating your own specific class derived from InvalidOperationException - make sure you only ever throw that (rather than plain InvalidOperationException), and then you can check whether any given instance has a concrete type that is your custom exception type or not.

like image 191
Jon Skeet Avatar answered Jan 26 '23 20:01

Jon Skeet