If you are a c# beginner or want to start learning the c# programming language, then this program will help you to understand the basics of c# programming. In this program, we are going to share C# program to demonstrate multiple exceptions.
Copy the below c# program and execute it in your Microsoft Visual Studio IDE (Integrated Development Environment ).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | using System; class Exercise { static void Main() { double Num1, Num2; double Result = 0.00; char op; try { Console.Write("Enter your First Number : "); Num1 = double.Parse(Console.ReadLine()); Console.Write("Enter an Operator (+, -, * or /): "); op = char.Parse(Console.ReadLine()); if (op != '+' && op != '-' && op != '*' && op != '/') throw new Exception(op.ToString()); Console.Write("Enter your Second Number :"); Num2 = double.Parse(Console.ReadLine()); if (op == '/') if (Num2 == 0) throw new DivideByZeroException("Division by zero is not allowed"); Result = Calculator(Num1, Num2, op); Console.WriteLine("\n{0} {1} {2} = {3}", Num1, op, Num2, Result); } catch (FormatException) { Console.WriteLine("The number you typed is not valid"); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine("Operation Error: {0} is not a valid op", ex.Message); } Console.Read(); } static double Calculator(double v1, double v2, char op) { double Result = 0.00; switch (op) { case '+': Result = v1 + v2; break; case '-': Result = v1 - v2; break; case '*': Result = v1 * v2; break; case '/': Result = v1 / v2; break; } return Result; } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.