How to automatically throw exceptions

If you end the call HttpResponse.Endinside the catch try block, it ThreadAbortExceptionwill be re-raised automatically. I assume this is so, even if you complete the catch try block in the try catch block.

How can I do the same thing? I do not have a real application for this.

namespace Program
{
    class ReJoice
    {
        public void End() //This does not automatically re-raise the exception if caught.  
        {
            throw new Exception();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ReJoice x = new ReJoice();
                x.End();
            }
            catch (Exception e) {}
        }
    }
}
+3
source share
3 answers

You cannot modify the usual exceptions to have this behavior. ThreadAbortException has special support for this, that you cannot implement yourself in C #.

ThreadAbortException is a special exception that can be detected, but it will be automatically raised again at the end of the catch block.

+7

, throw.

throw;

catch. , throw e;, .

, , , , , , , . , , , . ThreadAbortException CLR, .

- :

namespace Program
{
    class ReJoice
    {
        public void End()
        {
            throw new Exception();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ReJoice x = new ReJoice();
                x.End();
            }
            catch (Exception e) 
            {
                throw;
            }
        }
    }
}
+4

?

namespace Program
{
    class ReJoice
    {
        public void End() //This does not automatically re-raise the exception if caught.  
        {
            throw new Exception();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ReJoice x = new ReJoice();
                x.End();
            }
            catch (Exception e) {
               throw e;
            }
        }
    }
}

Edit: It does not throw an exception because the catch value is intended to handle the exception. It is up to you as the caller of x.End () what you want to do when an exception occurs. By catching the exception and doing nothing, you say you want to ignore the exception. In the catch block, you can display a message box or register an error message, completely destroy the application or reinstall the error with additional information, wrapping an exception:

throw new Exception("New message", e);
+1
source

Source: https://habr.com/ru/post/1740376/


All Articles