简体   繁体   English

引发和捕获异常#2

[英]Throwing and catching exceptions #2

I've a console application that zips files and then send them via email. 我有一个控制台应用程序,可以压缩文件,然后通过电子邮件发送它们。 It does that every hour. 它每小时都会这样做。 I wanted to know what kind of exceptions should I handle ? 我想知道应该处理哪种异常? Let say if there's no network available when the process starts. 假设启动过程时是否没有可用的网络。 What exception will I get then ? 那我会得到什么例外呢? And what can be the other ways this can fail. 失败的其他方式可能是什么。 So basically I'm trying to figure out what exceptions I should catch. 所以基本上我正在尝试找出应该捕获的异常。

I got something like this 我有这样的东西

try
{
    // zips files and send email
}      
catch(System.Net.Mail.SmtpException e)
{
    Console.WriteLine(e.toString());
}
catch(exception e)
{

}

Ideally, the libraries you're using will come with documentation that will list all of the types of exceptions that can be thrown, if not then you'll have to use a tool like Reflector to inspect the methods you're using to find their thrown exceptions. 理想情况下,您所使用的库将随附文档,其中列出了所有可能引发的异常类型,否则,您将不得不使用Reflector之类的工具来检查用于查找其异常的方法引发异常。

For example, the SmtpClient.Send method (as documented here http://msdn.microsoft.com/en-us/library/swas0fwc.aspx ) lists these exceptions: 例如, SmtpClient.Send方法(如http://msdn.microsoft.com/en-us/library/swas0fwc.aspx所述 )列出了以下异常:

  • ArgumentNullException ArgumentNullException
  • InvalidOperationException InvalidOperationException
  • ObjectDisposedException ObjectDisposedException
  • SmtpException SmtpException
  • SmtpFailedRecipientsException SmtpFailedRecipientsException

Remember to catch exceptions in descending order of derivity, ie catch SmtpFailedRecipientsException before SmtpException because SmtpFailedRecipientsException derives from SmtpException . 记住要以衍生性的降序来捕获异常,即在SmtpException之前捕获SmtpFailedRecipientsException ,因为SmtpFailedRecipientsException派生自SmtpException

You can review the MSDN pages to view what types of exceptions certain methods or constructors will throw from .NET libraries. 您可以查看MSDN页面,以查看某些方法或构造函数将从.NET库引发的异常类型。 Such as, for the SmtpClient.Send method , it throws the following exceptions: 例如,对于SmtpClient.Send方法 ,它将引发以下异常:

  • ArgumentNullException ArgumentNullException
  • InvalidOperationException InvalidOperationException
  • ObjectDisposedException ObjectDisposedException
  • SmtpException SmtpException
  • SmtpFailedRecipientsException SmtpFailedRecipientsException

There is also a link of common exception types that you may be interested in located here . 您可能也对这里有一个常见异常类型的链接感兴趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM