FunctionX Logo

C# Examples: Nesting Exceptions

 

Introduction

This is an example of handling an exception inside of another, which is referred to as nesting:

using System;

class Exercise
{
	static void Main()
	{
		double Operand1, Operand2;
		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 a number, an operator, and a number:");
			Operand1 = double.Parse(Console.ReadLine());
			Operator = char.Parse(Console.ReadLine());
			Operand2 = double.Parse(Console.ReadLine());

			if( Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/')
				throw new Exception(Operator.ToString());

			switch(Operator)
			{
				case '+':
					Result = Operand1 + Operand2;
					Console.WriteLine("\n{0} + {1} = {2}", Operand1, Operand2, Result);
					break;

				case '-':
					Result = Operand1 - Operand2;
					Console.WriteLine("\n{0} - {1} = {2}", Operand1, Operand2, Result);
					break;

				case '*':
					Result = Operand1 * Operand2;
					Console.WriteLine("\n{0} * {1} = {2}", Operand1, Operand2, Result);
					break;

				case '/':
					// The following exception is nested in the previous try
					try 
					{
						if(Operand2 == 0)
							throw new DivideByZeroException("Division by zero is not allowed");

						Result = Operand1 / Operand2;
						Console.WriteLine("\n{0} / {1} = {2}", Operand1, Operand2, Result);
					}
					catch(DivideByZeroException ex)
					{
						Console.WriteLine(ex.Message);
					}
					break;
			}
		}
		catch(Exception ex)
		{
			Console.WriteLine("\nOperation Error: {0} is not a valid operator", ex.Message);
		}
	}
}
 

Home Copyright 2004 FunctionX, Inc.