Enter Your First Number : 10 Enter an Operator (+, -, * or /) : , Operation Error : , is not a Valid Operator
Users Online
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Latest Articles
Articles Hierarchy
C# Program to Demonstrate Multiple Exceptions
C# Program to Demonstrate Multiple Exceptions
This is a C# Program to demonstrate multiple exceptions.
This C# Program Demonstrates Multiple Exceptions.
Here exceptions in C# provide a structured, uniform, and type-safe way of handling both system-level and application-level error conditions.
Here is source code of the C# Program to Demonstrate Multiple Exceptions. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
/* * C# Program to Demonstrate Multiple Exceptions */ 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; } }
In this C# program, we are reading the first number using ‘num1’ variable and an operator using ‘op’ variable. If condition statement is used to check the value of operator ‘op’ variable is not equal to arithmetic operator ((+, -, * or /) using logical AND Operator if the condition is true then execute the statement.
Then we are reading the second number using ‘Num2’ variable. If condition statement is used to check that the value of ‘op’ variable is equal to ‘/’, if the condition is true then executes the statement. Using ‘Result’ variable perform the Calculator() function by passing the value ‘Num1’, ‘Num2’ and ‘op’ variables as an argument.
In Calculator() function perform the arithmetic operations using switch case statement. Here Exceptions in C# provide a structured, uniform, and type-safe way of handling both system-level and application-level error conditions. Using try and catch, an error message is displayed when the error occurs.