All articles(网络文学目录) All Pictures(图片目录) All Softwares(软件目录)

 
C#中的try

Writer: qq Article type: Programming skills(编程技巧) Time: 2014/7/11 9:20:13 Browse times: 350 Comment times: 0

C#中的try


Head photo

Go homepage
Upload pictures
Write articles

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);
}
}
}
}





There are 0 records,
Comment:
Must be registered users to comment(必须是注册用户才能发表评论)

Disclaimer Privacy Policy About us Site Map
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.