Here is the code that I wrote to understand how exception handling works:
using System;
using System.IO;
class ExceptionHandling
{
public static void Main()
{
try
{
StreamReader streamReader = new StreamReader("C:\\Sample Files\\Data.txt");
Console.WriteLine(streamReader.ReadToEnd());
streamReader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
}
I understand the try
block, but I am having a hard time to understand how catch
block works. I know that Exception
is a class
and ex.Message
is the exceptions message.
- My questions is what is
ex
? If this is an object, then how can we use without instantiation? And what does putting Exception ex into parameter of catch do? - And finally are
try
andcatch
methods? If they yes, are they inSystem
namespace?