difference in throw, throw new, throw ex

What is the difference and why throw an exception at all? I understand that if we have a method called somewhere in which there may potentially be an error, we should "throw" an exception from there to a place from where the method is not mediocre called,

Author: Kioshilol, 2019-10-11

1 answers

To simplify it completely, there are only two constructions, throw e and throw.

The first one - throw e - takes the exception object and throws it. This object will catch the first matching catch higher up the stack. At the moment of throwing, the call stack is bound to the exception, from the place where throw e was called and higher. By catching this e above, you can find out the exact location where throw e was called.

The second one - throw - can only be used in catch, and it throws what is caught by this catch the exception is raised as if you didn't catch it.

Simple example

private static void B()
{
    throw new Exception();
}

private static void A()
{
    try
    {
        B();
    }
    catch (Exception e)
    {
        throw;
    }
}

public static void Main(string[] args)
{
    try
    {
        A();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

Method A catches the exception, but pretends not to catch it (calls throw). Therefore, the console outputs

System.Exception: Exception of type 'System.Exception' was thrown.
   at ConsoleApp13.Program.B() in ...
   at ConsoleApp13.Program.A() in ...
   at ConsoleApp13.Program.Main(String[] args) in ...

If method A is rewritten as

private static void A()
{
    try
    {
        B();
    }
    catch (Exception e)
    {
        throw e;
    }
}

Then the information that the exception was created and thrown in B will be lost:

System.Exception: Exception of type 'System.Exception' was thrown.
   at ConsoleApp13.Program.A() in 
   at ConsoleApp13.Program.Main(String[] args) in 

Then the behavior will be the same as if in A it was written simply throw new Exception();

 9
Author: PashaPash, 2019-10-11 11:21:36