c#如何 抛出异常

startPort = Convert.ToInt16(txtStart.Text.Trim());
2024-12-25 12:23:37
推荐回答(5个)
回答1:

throw 用来抛出异常,可自己编写代码,抛出所需要的异常。

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CheckedAndUnchecked
{
    class Program
    {
        static void Main(string[] args)
        {
            int month;
            string b;
            Console.WriteLine("请输入月份的值:");
            b = Console.ReadLine();
            month = int.Parse(b);
            switch (month)
            {
                case 1:
                    Console.WriteLine("January");
                    break;
                case 2:
                    Console.WriteLine("Feburary");
                    break;
                case 3:
                    Console.WriteLine("March");
                    break;
                case 4:
                    Console.WriteLine("April");
                    break;
                case 5:
                    Console.WriteLine("May");
                    break;
                case 6:
                    Console.WriteLine("June");
                    break;
                case 7:
                    Console.WriteLine("July");
                    break;
                case 8:
                    Console.WriteLine("August");
                    break;
                case 9:
                    Console.WriteLine("September");
                    break;
                case 10:
                    Console.WriteLine("October");
                    break;
                case 11:
                    Console.WriteLine("Novemer");
                    break;
                case 12:
                    Console.WriteLine("December");
                    break;
                default:
                    throw new ArgumentOutOfRangeException("不存在的月份"); // throw
            }
        }
    }
}

回答2:

throw new Exception("错误消息"); 

手动抛出异常。


或者:

            try
            {
                int a = Convert.ToInt32("abc");
            }
            catch (Exception ex)
            {
                throw ex;
            }

回答3:

try
{
startPort = Convert.ToInt16(txtStart.Text.Trim());

}catch(Exception e)
{
throw new Exception("字符串转化int类型失败:"+e.Message);
}

回答4:

Int16 startPort;
if (Int16.TryParse(txtStart.Text.Trim(), out startPort))
{
    //转换成功的到startPort
}
else
{
    //这里就可以提示要输入数字
}

回答5:

//异常报错

try
{

//这里写程序方法

}catch(Exception e)
{
// e.Message 为报错信息
Message.Show(e.Message);
}