Advertisement
bero_0401

Exceptions

Aug 18th, 2024
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.15 KB | Source Code | 0 0
  1. using data;
  2.  
  3. namespace CsharpCourse
  4. {
  5.  
  6.     internal class Program
  7.     {
  8.  
  9.  
  10.      
  11.  
  12.         static void Main(string[] args)
  13.         {
  14.             // you must use catch or finally with try
  15.             // finally -> always executes
  16.            
  17.             try
  18.             {
  19.                 int x = int.Parse("hello"); // if the exception occurs , it breaks from the try block
  20.                 Console.WriteLine(Divide(9, 3));
  21.                 Console.WriteLine(Divide(10, 0));
  22.                 Console.WriteLine(Divide(10, 2));
  23.             }
  24.             catch(DivideByZeroException ex)
  25.             {
  26.                 Console.ForegroundColor = ConsoleColor.Red;
  27.                 Console.WriteLine( "Can not divide By zero" ,ex.ToString());
  28.                 Console.ForegroundColor = ConsoleColor.White;
  29.             }
  30.             catch (Exception ex)
  31.             {
  32.                 Console.ForegroundColor = ConsoleColor.Red;
  33.                 Console.WriteLine( ex.ToString() );
  34.                 Console.ForegroundColor = ConsoleColor.White;
  35.             }
  36.             finally
  37.             {
  38.                 Console.ForegroundColor = ConsoleColor.Yellow;
  39.                 Console.WriteLine("Finally I am here!");
  40.                 Console.ForegroundColor = ConsoleColor.White;
  41.  
  42.             }
  43.             // if you want to make your exception -> throw
  44.             try
  45.             {
  46.  
  47.                 Console.WriteLine("Enter a number with five digits");
  48.                 string input = Console.ReadLine();
  49.                 if(input.Length != 5)
  50.                 {
  51.                     Console.ForegroundColor = ConsoleColor.Red;
  52.                     throw new Exception("IT is not a Five-digit number!");
  53.                     Console.ForegroundColor = ConsoleColor.White;
  54.                 }
  55.             }
  56.             finally
  57.             {
  58.                 Console.ForegroundColor = ConsoleColor.Yellow;
  59.                 Console.WriteLine("Try Again Later");
  60.                 Console.ForegroundColor = ConsoleColor.White;
  61.             }
  62.  
  63.         }
  64.  
  65.         static int Divide(int value , int divisor) {
  66.             return value/divisor;
  67.         }
  68.  
  69.  
  70.     }
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement