FunctionX Logo

C# Examples: Handling Multiple Exceptions

 

Introduction

This is an example of handling multiple exceptions in one method:

using System;

class Exercise
{
	static void Main()
	{
		double Number1, Number2;
		double Result = 0.00;
		char Operator;

	Console.WriteLine("This program allows you to perform an operation on two numbers");

		try 
		{
			Console.WriteLine("To proceed, enter");

			Console.Write("First Number:  ");
			Number1 = double.Parse(Console.ReadLine());

			Console.Write("An Operator (+, -, * or /): ");
			Operator = char.Parse(Console.ReadLine());
			if( Operator != '+' && Operator != '-' &&
				Operator != '*' && Operator != '/' )
				throw new Exception(Operator.ToString());

			Console.Write("Second Number: ");
			Number2 = double.Parse(Console.ReadLine());

			if( Operator == '/' )
				if( Number2 == 0 )
			throw new DivideByZeroException("Division by zero is not allowed");

			Result = Calculator(Number1, Number2, Operator);
		Console.WriteLine("\n{0} {1} {2} = {3}", Number1, Operator, Number2, Result);
		}
		catch(FormatException)
		{
			Console.WriteLine("The number you typed is not valid");
		}
		catch(DivideByZeroException ex)
		{
			Console.WriteLine(ex.Message);
		}
		catch(Exception ex)
		{
		Console.WriteLine("\nOperation Error: {0} is not a valid operator", ex.Message);
		}
	}
	
	static double Calculator(double Value1, double Value2, char Symbol)
	{
		double Result = 0.00;

		switch(Symbol)
		{
			case '+':
				Result = Value1 + Value2;
				break;

			case '-':
				Result = Value1 - Value2;
				break;

			case '*':
				Result = Value1 * Value2;
				break;

			case '/':
				Result = Value1 / Value2;
				break;
		}

		return Result;
	}
}
 

Home Copyright 2004 FunctionX, Inc.