try Statements and Exceptions - CSharp Custom Type

CSharp examples for Custom Type:try catch finally

Introduction

A try statement specifies a code block subject to error-handling or cleanup code.

A try statement looks like this:

try
{
  ... // exception may get thrown within execution of this block
}
catch (ExceptionA ex)
{
  ... // handle exception of type ExceptionA
}
catch (ExceptionB ex)
{
  ... // handle exception of type ExceptionB
}
finally
{
  ... // cleanup code
}

Consider the following program:

class Test
{
  static int Calc (int x) => 10 / x;

  static void Main()
  {
    int y = Calc (0);
    Console.WriteLine (y);
  }
}

Because x is zero, the runtime throws a DivideByZeroException, and our program terminates.

We can prevent this by catching the exception as follows:

Demo Code

using System;//from www  .j  av  a  2 s. c o m
class Test
{
   static int Calc (int x) => 10 / x;
   static void Main()
   {
      try
      {
         int y = Calc (0);
         Console.WriteLine (y);
      }
      catch (DivideByZeroException ex)
      {
         Console.WriteLine ("x cannot be zero");
      }
      Console.WriteLine ("program completed");
   }
}

Related Tutorials