1.  
  2. public class ThrowTestB
  3. {
  4. static void Main()
  5. {
  6. try
  7. {
  8. // TryCast produces an unhandled exception.
  9. TryCast();
  10. }
  11. catch (Exception ex)
  12. {
  13. // Catch the exception that is unhandled in TryCast.
  14. Console.WriteLine
  15. ("Catching the {0} exception triggers the finally block.",
  16. ex.GetType());
  17.  
  18. // Restore the original unhandled exception. You might not
  19. // know what exception to expect, or how to handle it, so pass
  20. // it on.
  21. throw;
  22. }
  23. }
  24.  
  25. public static void TryCast()
  26. {
  27. int i = 123;
  28. string s = "Some string";
  29. object obj = s;
  30.  
  31. try
  32. {
  33. // Invalid conversion; obj contains a string, not a numeric type.
  34. i = (int)obj;
  35.  
  36. // The following statement is not run.
  37. Console.WriteLine("WriteLine at the end of the try block.");
  38. }
  39. finally
  40. {
  41. // Report that the finally block is run, and show that the value of
  42. // i has not been changed.
  43. Console.WriteLine("\nIn the finally block in TryCast, i = {0}.\n", i);
  44. }
  45. }
  46. // Output:
  47. // In the finally block in TryCast, i = 123.
  48.  
  49. // Catching the System.InvalidCastException exception triggers the finally block.
  50.  
  51. // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
  52. }
  53.