| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 567 人关注过本帖
标题:请问以下程序中catch中的return有什么用
只看楼主 加入收藏
恶魔城主
Rank: 1
等 级:新手上路
帖 子:8
专家分:7
注 册:2012-3-11
结帖率:75%
收藏
已结贴  问题点数:20 回复次数:2 
请问以下程序中catch中的return有什么用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using

namespace 文件使用
{
    class Program
    {
        public static void Main()
        {
            string[] CLA = Environment.GetCommandLineArgs();
            Console.WriteLine(CLA[0]);
              if (CLA.Length < 3)
             {
               Console.WriteLine("Format:{0} orig-file new-file",CLA[0]);

            }
            else {
          string origfile;
            origfile = CLA[1];
            string newfile;
            newfile = CLA[2];
   try
              {
                  File.Copy(origfile, newfile );
              }
              catch () { Console.WriteLine("{0}dose not exist", origfile);
              return;
              }
              catch (Exception e) { Console.WriteLine("An exception was thrown trying to copy file.");
              return;
              }


          Console.WriteLine("Copy...");

            }

           
       Console.WriteLine(".....Done");
        }
    }
}
搜索更多相关主题的帖子: void return public 
2012-07-24 18:27
Anox
Rank: 1
等 级:新手上路
帖 子:2
专家分:5
注 册:2012-7-24
收藏
得分:2 
你这个是 try...catch语句啊。
 
如果catch未捕捉到相应的异常,return表示相应的程序终止,返回未执行该事件前的状态
如果catch捕捉到了相应的异常,就执行后面的代码。


[ 本帖最后由 Anox 于 2012-7-24 19:28 编辑 ]
2012-07-24 19:26
yhlvht
Rank: 13Rank: 13Rank: 13Rank: 13
等 级:贵宾
威 望:36
帖 子:707
专家分:4405
注 册:2011-9-30
收藏
得分:18 
以这个例子来说,如果File.Copy(origfile, newfile );这句正确执行,没有报错,那么程序会接着执行Console.WriteLine("Copy...");以及Console.WriteLine(".....Done");
如果File.Copy(origfile, newfile );报错,就会执行catch里面的语句,如果是文件未找到,执行 Console.WriteLine("{0}dose not exist", origfile);其它错误执行Console.WriteLine("An exception was thrown trying to copy file.");之后程序会遇到return,那么Console.WriteLine("Copy...");以及Console.WriteLine(".....Done");就不会再被执行了。
那么,在catch中加return的目的就是,如果程序报错了,就退出这个方法吧,后面的语句就不要再执行了,那是给没报错的时候执行的。




2012-07-25 11:56
快速回复:请问以下程序中catch中的return有什么用
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.018121 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved