火影之轮回杀生丸:C#中的try

来源:百度文库 编辑:偶看新闻 时间:2024/04/28 03:23:07

  try-catch错误处理表达式允许将任何可能发生异常情形的程序代码放置在try{}程序代码块进行监控,真正处理错误异常的程序代码则被放置在catch{}块内,一个try{}块可对应多个catch{}块。
C#中的try-catch语句使用方法
try-catch错误处理表达式允许将任何可能发生异常情形的程序代码放置在try{}程序代码块进行监控,真正处理错误异常的程序代码则被放置在catch{}块内,一个try{}块可对应多个catch{}块。
示例
try-catch语句写入多个catch的使用
通过两个catch语句进行捕获异常,它们分别是ArgumentNullException异常和Exception异常。程序代码如下:
using System;
class MainClass
{
static void ProcessString(string str)
{
if (str == null)
{
throw new ArgumentNullException();
}
}
static void Main()
{
// http://www.isstudy.com
Console.WriteLine("输出结果为:");
try
{
string str = null;
ProcessString(str);
}
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception.", e.Message);
}
catch (Exception e)
{
Console.WriteLine("{0} Second exception.", e.Message);
}
}
}
键运行程序,运行结果如图1所示。

图1 try-catch语句
完整程序代码如下:
★★★★★主程序文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.Text;
namespace _3_16
{
class Program
{
static void ProcessString(string str)
{
if (str == null)
{
throw new ArgumentNullException();
}
}
static void Main()
{
// http://www.isstudy.com
Console.WriteLine("输出结果为:");
try
{
string str = null;
ProcessString(str);
}
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception.", e.Message);
}
catch (Exception e)
{
Console.WriteLine("{0} Second exception.", e.Message);
}
}
}
}