C#中的异常处理初学者

时间:2014-12-19 04:56:59

标签: c# exception

我正在尝试自己学习C#。 在下面的代码中,我只想在没有找到异常的情况下执行 main方法是否可能 ????

任何人都可以帮助我吗

代码

public abstract class AbsClass
    {
        // Abstract Method
        public abstract int DivTwoNumbers(int a, int b);

    }

    class Program : AbsClass
    {
        public int result { get; set; }

        public override int DivTwoNumbers(int a, int b)
        {
            try
            {
                result = a / b;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Second Number was " + e.Message);
            }

            return result;
        }

        static void Main(string[] args)
        {
            AbsClass prog = new Program();
            int div = prog.DivTwoNumbers(10, 0);
            Console.WriteLine("Division Of Number Is : {0} ", div);
        }

    }

2 个答案:

答案 0 :(得分:3)

If I understand you right, you don't want to print number if division is incorrect - 从我的评论到可能的答案。

public override int DivTwoNumbers(int a, int b)
{
    return a / b;
}


static void Main(string[] args)
{
    AbsClass prog = new Program();
    try
    {
        int div = prog.DivTwoNumbers(10, 0);
        Console.WriteLine("Division Of Number Is : {0} ", div);
    }
    catch (DivideByZeroException e)
    {
        Console.WriteLine("DivideByZeroException. Second Number was " + e.Message);
    }
    catch(Exception ex)
    {
        Console.WriteLine("ErrorMessage :" + ex); // will also print exception details (edit by `KCdod`)
    }

}

答案 1 :(得分:0)

Main方法始终是第一个执行的方法,您必须在Main方法中调用DivTwoNumbers:

static void Main(string[] args)
{
    try
    {
        DivTwoNumbers(10, 0);
        //continue ...
    }
    catch(Exception ex)
    {
        //break...
    }
}