Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)qq
published in(发表于) 2014/7/11 9:20:13
C#中的try

C#中的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);

}

}

}

}




If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759