轻松学习C#的异常处理

2019-12-30 11:17:58王旭

例三:将字符串转换为整数的异常


using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
 
namespace Text 
{ 
 class Program 
 { 
  static void Main(string[] args) 
  { 
   string str = "string"; 
   try 
   { 
    int returnInt; 
    returnInt = Program.ConvertStringToInt(str);//调用转换 
    Console.Write(returnInt); 
   } 
   catch (FormatException a) 
   { 
    Console.WriteLine(a.Message); 
   } 
   Console.ReadLine(); 
  } 
  private static int ConvertStringToInt(string str)//定义转换函数 
  { 
   int intNum = 0; 
   try 
   { 
    intNum = Convert.ToInt32(str); 
    return intNum; 
   } 
   catch 
   { 
    throw new FormatException("转换错误");//引发异常 
   } 
  } 
 
 } 
} 

输出的结果为:

轻松学习C#的异常处理

四、自定义异常类
          C#语言虽然预定义了许多异常类,但是,在有些场合,创建自己的异常类可能会方便。自定义异常类是通过继承System.Exception类来创建自己的异常类。其步骤是:
(1)声明一个异常,格式如下:class  异常类名:Exception{ }
(2)引发自己的异常,格式如下: throw(ExceptionName);
 例四:定义一个异常类MyException,然后引发这个异常类。


using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
 
namespace Text 
{ 
 class MyException : SystemException { }//声明异常 
 class Program 
 { 
  static void Main(string[] args) 
  { 
   try 
   { 
    Console.WriteLine("引发异常前我是被执行的");//引发异常前的提示 
    throw new MyException(); 
    Console.WriteLine("因为已经引发异常,所以我不能被执行"); 
   } 
   catch (MyException) 
   { 
    Console.WriteLine("引发异常"); 
   }  
   Console.ReadLine(); 
  } 
 
 } 
} 

输出的结果为:

轻松学习C#的异常处理

以上就是本文的全部内容,希望对大家的学习有所帮助。