0

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 and catch methods? If they yes, are they in System namespace?
Nikolai Samteladze
  • 7,699
  • 6
  • 44
  • 70
JCronin
  • 215
  • 1
  • 2
  • 6
  • Close-voters: Please quote the part of the question which asked us to "recommend or find a book, tool, software library, tutorial or other off-site resource". – Blorgbeard Jul 30 '15 at 20:01

3 Answers3

5

ex is a variable of type Exception.

When code elsewhere fails, it will do something like throw new Exception("some message here");.

The throw keyword causes the exception (created by new) to be passed up the stack, and if it hits your catch, that code will execute with ex pointing to that exception object.

throw, try, and catch are not functions, they are keywords. They're language features like foreach and if.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • Thank you for your answer :) But can you answer my question again? If ex is a variable how can we use ex.Message. I thought in order to get property from a class ex has to be an object. Am I misunderstanding sth? Thank you again – JCronin Jul 30 '15 at 00:44
  • Yes, you are misunderstanding what "variable" and "object" means, I think. When you declare an `int` like `int number = 123;`, `number` is a variable. It points to an integer, not an object, but it's still a variable. Likewise, `ex` is a variable which points to an object in memory. You could say "ex is an object", but that's short-hand for "the thing that the variable named "ex" points to is an object". – Blorgbeard Jul 30 '15 at 01:12
  • @JCronin `ex` is a variable of type `Exception`, so it holds a reference to an object of type `Exception` (or a type derived from `Exception`). – Ergwun Jul 30 '15 at 01:16
4

ex is a variable referring to an exception object that is instantiated by either the object that raised the exception, one of its dependencies, or the .NET runtime.

You can create your own exceptions like any object, and then throw them:

var myException = new MyCustomException(/*...*/);
throw myException;

try-catch is a statement that is part of the syntax of the C# language.

The catch part does not need to reference the exception variable if you do not need to access any of its members in your handling code. The following is valid syntax:

try {
    // some code that might throw IO exception
catch (IOException) {
    Console.WriteLine("Exception thrown.");
}

Bonus tips:

  • It is generally bad practice to catch the base class Exception - you should typically catch the most specific derived exception that you are trying to handle in your catch clause.
  • When you are using a class that implements IDisposable like StreamReader, you should consider using the using statement.
Community
  • 1
  • 1
Ergwun
  • 12,579
  • 7
  • 56
  • 83
2

If the code crashes anywhere the it will have because someone has instantiated and thrown (C# throw keyword) an instance of an Exception (most likely a subtype such as InvalidOperationException).

If this exception is raised inside the try, the catch will attempt to handle it by checking if it can be derived from Exception (which all .Net Exceptions do).

If you define a variable to hold the instance of the exception on your catch block the runtime will assign the exception to it.

So ex will be set by the runtime to the exception that occurred. Have a look using the Debugger to see more information about it.

You can handle just specific exceptions like so:

catch (NullReferenceException nre) { HandleNRE(nre); } //nre will be a NullReferenceException 
catch (InvalidOperationException ioe) { HandleIOE(ioe); } //ioe will be an InvalidOperationException 
catch (Exception e) { HandleEverythingElse(e); } //e will be whatever was thrown.

You can also have catch blocks without an ex, e.g.

catch (NullReferenceException) { /* Do nothing, who cares about nulls. */ }
DaveShaw
  • 52,123
  • 16
  • 112
  • 141