在这种情况下抛出什么类型的异常? [英] What type of exception to throw in this case?

查看:175
本文介绍了在这种情况下抛出什么类型的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写它使用自动化控制其他程序C#应用程序。当然该程序必须运行我的程序工作。当我的程序查找应用程序并不能找到它,我想抛出一个异常(现在以后我当然可以尝试打开应用程序,或者告诉用户打开它,或...)。



我应该实现一个自定义异常 - 或者使用现有NotSupportedException异常(或其他.NET例外之一)。如果一个自定义异常,你有什么建议吗?我想实现一个自定义异常我把它叫做MyAppNameException,然后只用该消息宣布的问题是什么呢?



在那里抛出异常的一般规则的方式,让你的程序更具可读性和用户友好的,还是我只是给这太多心思?!)



感谢


解决方案

  1. 首先,定义 MyAppCustomException 作为一个抽象基类。


  2. 然后从它继承与 AppNotFoundCustomException




这样,您就可以赶上的所有的从你的应用程序异常,或只是具体的人。



下面是一些示例代码,说明了这一概念:

 公共抽象类MyAppCustomException:系统。异常
{
内部MyAppCustomException(字符串消息)
:基地(消息)
{
}

内部MyAppCustomException(字符串消息,系统.Exception的InnerException)
:基地(消息的InnerException)
{
}
}

公共类AppNotFoundCustomException:MyAppCustomException
{
公共AppNotFoundCustomException():基地(找不到应用程序)
{
}
}

和这里的客户端的try / catch 例如:

 
{
//做的东西
}
赶上(AppNotFoundCustomException)
{
//我们知道如何处理这
}
赶上(MyAppCustomException)//基类
{
//我们不知道如何处理这个问题,但我们知道它与我们的应用程序$ b $问题b}


I'm writing a c# application which uses automation to control another program. Naturally that program must be running for my program to work. When my program looks for the application and can't find it I'd like to throw an exception (for now later of course I could try opening the application, or telling the user to open it, or ...).

Should I implement a custom exception - or use the existing NotSupportedException (or one of the other .NET exceptions). If a custom exception, what would you suggest? I was thinking of implementing a custom exception I'd call it MyAppNameException and then just use the message to declare what the problem was?

Are there any general rules to throwing exceptions in a way that makes your program more readable and user friendly, or am I just giving this too much thought :)?

Thanks!

解决方案

  1. First, define MyAppCustomException as an abstract base class.

  2. Then inherit from it with AppNotFoundCustomException.

This way you can catch all exceptions from your app, or just specific ones.

Here's some example code that illustrates the concept:

public abstract class MyAppCustomException : System.Exception
{
    internal MyAppCustomException(string message)
        : base(message)
    {
    }

    internal MyAppCustomException(string message, System.Exception innerException)
        : base(message,innerException)
    {            
    }
}

public class AppNotFoundCustomException : MyAppCustomException
{
    public AppNotFoundCustomException(): base("Could not find app")
    {
    }
}

And here's a client try/catch example:

try 
{
   // Do Stuff
}
catch(AppNotFoundCustomException)
{
   // We know how to handle this
}
catch(MyAppCustomException) // base class
{
   // we don't know how to handle this, but we know it's a problem with our app
}

这篇关于在这种情况下抛出什么类型的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆