在c#中,(1)编写一个自定义异常类MyException,在构造函数中输出“不是正整数”。 (

2025-03-12 22:42:21
推荐回答(2个)
回答1:

using System;

namespace ConsoleApplication2
{
    // 定义自己的异常,继承自Exception
    public class MyException : Exception
    {
        public override string Message
        {
            get { return "不是正整数"; }
        }
    }
    public class Computer
    {
        public int GetMax(int x, int y)
        {
            if (x < 1 || y < 1)
            {
                // 抛出异常
                throw new MyException();
            }
            if (x > y) 
                return x;
            else 
                return y;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Computer c = new Computer();
            try
            {
                int max = c.GetMax(0, 100);
            }
            catch (MyException me)
            {
                Console.WriteLine(me.Message);
            }
        }
    }
}

 运行结果

回答2:

class Program
{
    static void Main(string[] args)
    {
        Computer computer = new Computer();
        computer.GetMax(0, 100);
    }
}
 
class MyException : Exception
{
    public MyException()
    {
        Console.WriteLine("不是正整数。");
    }
}
 
class Computer
{
    public int GetMax(int a, int b)
    {
        if (a < 1 || b < 1)
            throw new MyException();
        else
            return Math.Max(a, b);
    }
}