When you set up a catch block:
try
{
...
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("\n\n");
Console.WriteLine(e.StackTrace);
}
Or indeed, declare any variable:
string s;
Button b;
StreamReader str;
You aren't creating an instance of the class, you are declaring a place to store a
reference to an instance of the class - a container if you like.
Just as a cup can contain coffee, the cup itself is not the wonderful liquid - indeed, when you finish drinking the Coffee instance, you can reuse the same cup to contain a new instance of Coffee, and start drinking that.
As you have noticed, in order to use a class, you need (at some point) to create a new instance of it, and load that into a variable of some form - but you don't always want to create a new one every time. If you write a method that returns a Streamreader:
private StreamReader GetStream(path)
{
return new StreamReader(path);
}
You can create a variable and fill it with an instance without explicitly using the
new
keyword:
StreamReader str = GetStream(@"C:\Users\IBM_ADMIN\Downloads\IBM\metal.txt");
And that is what effectively happens when you write a catch block: the Exception has already created the new Exception class instance, and you are declarign a variable to put it into. Using
new
here would imply that it was created at that point, and was unrelated to the error which created and threw the actual exception you are trying to recover information for.