finally blocks always execute, even when no exception occurs. - CSharp Custom Type

CSharp examples for Custom Type:try catch finally

Description

finally blocks always execute, even when no exception occurs.

Demo Code




using System;/*  w  w w  .  ja  va 2 s. c o m*/

class UsingExceptions
{
   static void Main()
   {
      // Exception occurs and is caught in called method
      ThrowExceptionWithCatch();

      // Exception occurs, but is not caught in called method because there is no catch block.
      Console.WriteLine("\nCalling ThrowExceptionWithoutCatch");

      try{
         ThrowExceptionWithoutCatch();
      }catch{
         Console.WriteLine("Caught exception from ThrowExceptionWithoutCatch in Main");
      }
      // Exception occurs and is caught in called method, then rethrown to caller.
      try
      {
         ThrowExceptionCatchRethrow();
      }
      catch
      {
         Console.WriteLine("Caught exception from ThrowExceptionCatchRethrow in Main");
      }
   }



   // throws exception and catches it locally
   static void ThrowExceptionWithCatch()
   {
      try
      {
         Console.WriteLine("In ThrowExceptionWithCatch");
         throw new Exception("Exception in ThrowExceptionWithCatch");
      }
      catch (Exception exceptionParameter)
      {
         Console.WriteLine($"Message: {exceptionParameter.Message}");
      }
      finally
      {
         Console.WriteLine(
            "finally executed in ThrowExceptionWithCatch");
      }

      Console.WriteLine("End of ThrowExceptionWithCatch");
   }

   static void ThrowExceptionWithoutCatch()
   {
      try
      {
         Console.WriteLine("In ThrowExceptionWithoutCatch");
         throw new Exception("Exception in ThrowExceptionWithoutCatch");
      }
      finally
      {
         Console.WriteLine(
            "finally executed in ThrowExceptionWithoutCatch");
      }

      // unreachable code; logic error
      Console.WriteLine("End of ThrowExceptionWithoutCatch");
   }

   // throws exception, catches it and rethrows it
   static void ThrowExceptionCatchRethrow()
   {
      // try block throws exception
      try
      {
         Console.WriteLine("In ThrowExceptionCatchRethrow");
         throw new Exception("Exception in ThrowExceptionCatchRethrow");
      }
      catch (Exception exceptionParameter)
      {
         Console.WriteLine("Message: " + exceptionParameter.Message);

         // rethrow exception for further processing
         throw;

         // unreachable code; logic error
      }
      finally
      {
         Console.WriteLine(
            "finally executed in ThrowExceptionCatchRethrow");
      }

      // any code placed here is never reached
      Console.WriteLine("End of ThrowExceptionCatchRethrow");
   }
}

Related Tutorials