ellapt

T12.1.TryCatchFinally

Jan 25th, 2013
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. using System;
  2.  
  3. class TryCatchFinally
  4. {
  5. static void Main()
  6. {
  7. Console.WriteLine("Read an integer number, calculate and print its square root.\nUse try-catch-finally to handle exceptions\n");
  8. int num;
  9. Console.Write("Enter an integer number: ");
  10. try
  11. {
  12. num = int.Parse(Console.ReadLine());
  13. double sqreRoot = Math.Sqrt(num);
  14. if (num < 0)
  15. {
  16. throw new System.ArgumentOutOfRangeException(
  17. "Invalid number: Sqrt for negative numbers is undefined!");
  18. }
  19. Console.WriteLine("The square root of {0} is {1}", num, sqreRoot);
  20. }
  21.  
  22. catch (FormatException)
  23. {
  24. Console.WriteLine("Invalid integer number!");
  25. }
  26. catch (OverflowException)
  27. {
  28. Console.WriteLine("Invalid number: too big to fit in Int32!");
  29. }
  30. catch (ArgumentOutOfRangeException)
  31. {
  32. Console.WriteLine("Invalid number: Sqrt for negative numbers is undefined!");
  33. }
  34. finally
  35. {
  36. Console.WriteLine("\nGood bye!");
  37. }
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment