抛出异常

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请输入你要进行的运算及数(+):");
            string f = Console.ReadLine();
            Console.Write("请输入第一个数:");
            int a = int.Parse(Console.ReadLine());
            Console.Write("请输入第二个数:");
            int b = int.Parse(Console.ReadLine());
            Console.Write("请输入答案:");
            int y = int.Parse(Console.ReadLine());
            Calldess dss=new Calldess();
            try
            {
                dss.Execute(f, a, b);
                throw new DivideByZeroException("尝试除以零吗?");
            }
            catch (DivideByZeroException e)
            {

                if (f == "/")
                {
                    if (b == 0)
                    {
                        Console.WriteLine(e.Message);
                    }
                }

            }
         

            Console.Read();

            
        }
    }
    public class Calldess
    {
        int sun;
        public int Execute(string op, int a, int b)
        {
            switch (op)
            {
                case "+":
                    sun = a + b;
                    break;
                case "-":
                    sun = a - b;
                    break;
                case "*":
                    sun = a * b;
                    break;
                case "/":

                    if (b == 0)
                    {
                        //Console.WriteLine("除数不能为零!");
                    }
                    else
                    {
                        sun = a / b;
                    }
                    break;

            }
            return sun;

        }
    }
}

 

<总结>

感觉这样写还是有点怪怪的。

原文地址:https://www.cnblogs.com/lizanqirxx/p/4964002.html