在编写程序时,有时可能要故意的引发异常,以便捕获异常。
引发异常的格式为
throw new 异常类(异常信息);
异常类:预定义的,自定义
异常信息:字符串“格式转换错误”
实例:为Program类定义一个将字符串转换成整数的私有静态方法ConvertStringToInt;它含有一个字符串类型参数,返回一个整数,然后通过这个使用方法将一个不能转换成整数的字符串转换成整数,故引发异常。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication14
{
class Program
{
private static int ConvertStringToInt(string mystr)
{
int outnum = 0;
try
{
outnum = Convert.ToInt32(mystr);
return outnum;
}
catch
{
throw new FormatException("格式转换不正确");
}
}
static void Main(string[] args)
{
string mystr = "www.baidu.com";
try
{
int myint;
myint = Program.ConvertStringToInt(mystr);
Console.WriteLine(myint);
}
catch(FormatException exf)
{
Console.WriteLine(exf.Message.ToString());
}
Console.ReadKey();
}
}
}