首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >何时使用try/catch块?

何时使用try/catch块?
EN

Stack Overflow用户
提问于 2009-11-12 15:19:11
回答 4查看 54.3K关注 0票数 50

我已经完成了我的阅读,并且理解了Try/Catch块的作用,以及为什么使用它很重要。但我仍然不知道何时/何地使用它们。有什么建议吗?我将在下面发布我的代码示例,希望有人有时间为我的示例提出一些建议。

代码语言:javascript
复制
    public AMPFileEntity(string filename)
    {
        transferFileList tfl = new transferFileList();
        _AMPFlag = tfl.isAMPFile(filename);
        _requiresPGP = tfl.pgpRequired(filename);
        _filename = filename.ToUpper();
        _fullSourcePathAndFilename = ConfigurationSettings.AppSettings.Get("sourcePath") + _filename;
        _fullDestinationPathAndFilename = ConfigurationSettings.AppSettings.Get("FTPStagePath") + _filename;
        _hasBeenPGPdPathAndFilename = ConfigurationSettings.AppSettings.Get("originalsWhichHaveBeenPGPdPath");
    }


    public int processFile()
    {

        StringBuilder sb = new StringBuilder();
        sb.AppendLine(" ");
        sb.AppendLine("    --------------------------------");
        sb.AppendLine("     Filename: " + _filename);
        sb.AppendLine("     AMPFlag: " + _AMPFlag);
        sb.AppendLine("     Requires PGP: " + _requiresPGP);
        sb.AppendLine("    --------------------------------");
        sb.AppendLine(" ");

        string str = sb.ToString();
        UtilityLogger.LogToFile(str);
        if (_AMPFlag)
        {
            if (_requiresPGP == true)
            {
                encryptFile();
            }
            else
            {
                UtilityLogger.LogToFile("This file does not require encryption. Moving file to FTPStage directory.");
                if (File.Exists(_fullDestinationPathAndFilename))
                {
                    UtilityLogger.LogToFile(_fullDestinationPathAndFilename + " alreadyexists. Archiving that file.");
                    if (File.Exists(_fullDestinationPathAndFilename + "_archive"))
                    {
                        UtilityLogger.LogToFile(_fullDestinationPathAndFilename + "_archive already exists.  Overwriting it.");
                        File.Delete(_fullDestinationPathAndFilename + "_archive");
                    }
                    File.Move(_fullDestinationPathAndFilename, _fullDestinationPathAndFilename + "_archive");
                }
                File.Move(_fullSourcePathAndFilename, _fullDestinationPathAndFilename);
            }
        }
        else
        {
            UtilityLogger.LogToFile("This file is not an AMP transfer file. Skipping this file.");
        }

            return (0);
    }


    private int encryptFile()
    {

        UtilityLogger.LogToFile("This file requires encryption.  Starting encryption process.");


        // first check for an existing PGPd file in the destination dir.  if exists, archive it - otherwise this one won't save.  it doesn't overwrite.
        string pgpdFilename = _fullDestinationPathAndFilename + ".PGP";



        if(File.Exists(pgpdFilename))
        {
            UtilityLogger.LogToFile(pgpdFilename + " already exists in the FTPStage directory.  Archiving that file." );
            if(File.Exists(pgpdFilename + "_archive"))
            {
                UtilityLogger.LogToFile(pgpdFilename + "_archive already exists.  Overwriting it."); 
                File.Delete(pgpdFilename + "_archive");
            }
            File.Move(pgpdFilename, pgpdFilename + "_archive"); 
        }

        Process pProc = new Process();
        pProc.StartInfo.FileName = "pgp.exe";

        string strParams = @"--encrypt " + _fullSourcePathAndFilename + " --recipient infinata --output " + _fullDestinationPathAndFilename + ".PGP";

        UtilityLogger.LogToFile("Encrypting file.  Params: " + strParams);
        pProc.StartInfo.Arguments = strParams;
        pProc.StartInfo.UseShellExecute = false;
        pProc.StartInfo.RedirectStandardOutput = true;
        pProc.Start();
        pProc.WaitForExit();

        //now that it's been PGPd, save the orig in 'hasBeenPGPd' dir
        UtilityLogger.LogToFile("PGP encryption complete.  Moving original unencrypted file to " +  _hasBeenPGPdPathAndFilename); 
        if(File.Exists(_hasBeenPGPdPathAndFilename + _filename + "original_which_has_been_pgpd"))
        {
            UtilityLogger.LogToFile(_hasBeenPGPdPathAndFilename + _filename + "original_which_has_been_pgpd already exists.  Overwriting it.");
            File.Delete(_hasBeenPGPdPathAndFilename + _filename + "original_which_has_been_pgpd");
        }
            File.Move(_fullSourcePathAndFilename, _hasBeenPGPdPathAndFilename + _filename + "original_which_has_been_pgpd");

        return (0);

    }
}

}

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-11-12 15:22:32

捕获异常的基本经验法则是捕获异常当且仅当您有一种有意义的方法处理它们

如果只记录异常并将其抛出堆栈,则不要捕获异常。它没有任何意义,也混淆了代码。

当您期望代码的某个特定部分出现故障时,以及如果您有相应的退路,请捕获异常。

当然,检查异常的情况总是需要使用try/catch块,在这种情况下,您没有其他选择。即使有选中的异常,也要确保正确地登录并尽可能干净地处理。

票数 110
EN

Stack Overflow用户

发布于 2009-11-12 15:44:35

就像其他人说过的那样,您希望在代码周围使用试图捕获块,这些代码可以抛出Exception和准备处理的代码。

关于您的特定示例,File.Delete可以抛出一些异常,例如IOExceptionUnauthorizedAccessException。在这种情况下,您希望您的应用程序做些什么?如果您尝试删除该文件,但其他人正在使用它,您将得到一个IOException

代码语言:javascript
复制
try
{    
    File.Delete(pgpdFilename + "_archive")
}
catch(IOException)
{
    UtilityLogger.LogToFile("File is in use, could not overwrite.");
   //do something else meaningful to your application
   //perhaps save it under a different name or something
}

另外,请记住,如果这确实失败了,那么您接下来在if块之外执行的if也将失败(再次到IOException --因为文件没有被删除,它仍然在那里,这将导致移动失败)。

票数 9
EN

Stack Overflow用户

发布于 2009-11-12 15:29:09

我被教导在任何可能发生多个错误且实际可以处理的方法/类中使用try/catch/finally。数据库事务、FileSystem I/O、流等。核心逻辑通常不需要try/catch/try。

try/ catch /最终的主要部分是可以有多个捕获,这样就可以创建一系列异常处理程序来处理非常具体的错误,或者使用一般的异常来捕获任何您看不到的错误。

在您的示例中,您使用的是File.Exists,这是很好的,但是磁盘上的另一个问题可能会引发另一个File.Exists无法处理的错误。是的,这是一个布尔方法,但是假设文件是被锁定的,如果你试图写到它会发生什么呢?有了这个捕获,您可以为一个罕见的场景做计划,但是如果不尝试/捕捉/最后,您可能会将代码暴露在完全不可预见的条件下。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1722964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档