从类中抛出异常 [英] Throwing exceptions from a class

查看:77
本文介绍了从类中抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个类,该类具有一个函数,该函数接收用逗号分隔的字符串,拆分字符串,解析值并最终返回带有这些值的新填充类.

由于该类是类库的一部分,因此我想知道哪种方法是向该类的最终用户抛出异常的最佳方法.

我当时想为每个格式错误的字段抛出一个异常,以提供有关问题出在哪里的有用信息,如下所示:

I''m writing a class that has a function which receives a comma separated string, split the string, parse the values and finally returns a new filled class with these values.

Since the class is part of a class library, i wish to know which is the best way of throwing exceptions to the final users of my class.

I was thinking to throw an exception for each malformed field to provide helpful messages about where is the problem, something like this:

Function FromString(ByVal fields As String) As FilledClass
   Dim aFields() AS String
   aFields = fields.Split(","c)

   Dim newClass AS New FilledClass()

   Try
      newClass.Field1 = Double.Parse(aFields(0))
   Catch ex AS Exception
      Throw New FormatException("Invalid string: field 1", ex)
   End Try

   Try
      newClass.Field2 = Integer.Parse(aFields(1))
   Catch ex AS Exception
      Throw New FormatException("Invalid string: field 2", ex)
   End Try

   Try
      newClass.Field3 = Byte.Parse(aFields(2))
   Catch ex AS Exception
      Throw New FormatException("Invalid string: field 3", ex)
   End Try

   Return newClass
End Function



这是一个好方法吗?还是最好只抛出一个一般异常?



Is this a good approach? or it is better throw only one general exception?

Function FromString(ByVal fields As String) As FilledClass
   Dim aFields() AS String
   aFields = fields.Split(","c)

   Dim newClass AS New FilledClass()

   Try
      newClass.Field1 = Double.Parse(aFields(0))
      newClass.Field2 = Integer.Parse(aFields(1))
      newClass.Field3 = Byte.Parse(aFields(2))
   Catch ex AS Exception
      Throw New FormatException("Invalid string", ex)
   End Try

   Return newClass
End Function





Is there a guideline for this or a best practice to do this?

推荐答案

通常,我喜欢抛出异常的方法.重新抛出异常也是一件好事.在这里,您将遵循基于异常的一劳永逸"方法.因此,我并不完全同意Naerling:使用TryParse并不总是最好的方法.此外,顾名思义,该TryParse可以使用try-catch块实现. (据我所记得,我看到的是真正的.NET源代码,实际上并非如此.)因此,您总是可以编写带有附加选项的自己的"TryParse".无论如何,阻止异常的传播是一件坏事,破坏了异常机制的目的.

问题是丢失了确切引起问题的字段的信息.这很不好,因为否则您可以将编辑框放在出现问题的位置.这里的方法是这样的:它取决于您从异常处理程序中真正需要多少细节.您可以以某种或多或少的细粒度方式做到这一点,但是再次,使用异常会给您带来更大的自由.如果将所有异常放在一起,则可以减少开发错误的空间,并且需要更少的代码.您可以决定每种情况的确切需求.

—SA
Generally, I like the approaches where an exception is thrown. Re-throwing of the exception is also a good thing. Here you follow the exception-based "throw-and-forget" approach. So, I do not fully agree with Naerling: using TryParse is not always the best thing. Besides, as the name suggests, this TryParse could be implemented using try-catch block. (As far as I remember the real .NET source code I saw, this is not the case, in fact.) So, you could always write your own "TryParse", with additional options. Anyway, blocking the propagation of an exception is a bad thing, defeating the purpose of exception mechanism.

The problem is that the information on which exactly field causes the problem is lost. This is bad because otherwise you could, say, focus a edit box where there is a problem. The approach here is this: it depends on how much detail would you really need from the exception handler. You could do it in a more or less fine-grain fashion, but again, using exceptions gives you more freedom. If you put all exceptions together, it gives you less room for development bugs and requires less code. You decide what exactly you need in each case.

—SA


最好是简单地使用采用DoubleIntegerByte的方法.假设您不希望这样做(无论出于何种原因),都不应使用解析 [ ^ ]并等待被抛出.最好使用 TryParse [,但是我想说调试该函数的输入并不难.调用这样的函数需要完全了解函数的内部.这样,用户已经知道该功能需要格式为"####0.####, ######0, ##0"String(嗯,有点).找出不符合要求的内容很容易,并且提及您的Exception中的哪个字段会增加很小的价值.
Better would be to simply use a method that takes a Double, Integer and Byte. Assuming you don''t want that (for whatever reason you have) you should not use Parse[^] and wait for an Exception to be thrown. Better would be to use TryParse[^] instead. It returns a Boolean which lets you know wether the String could be parsed or not, in which case you can take appropriate action.
Furthermore you could throw a detailed Exception, such as "Invalid String: Field 3", but debugging the input of the function is not very hard I would say. Calling a function such as this requires full knowledge of the internals of your function. As such the user would already know the function requires a String in format "####0.####, ######0, ##0" (well, sort of). Finding that it doesn''t meet the requirement is easy enough and mentioning which field it is in your Exception adds little value.


首先,例外的代价很高,所以您不这样做不想把它们扔多次.我的建议是,您收集异常中的所有问题,创建一个可以包含从异常派生的信息的类.无论如何,您可能都希望对此问题有特定的例外.然后,您可以捕获到此特定的排他信息,它将包含有关该问题的所有信息.由于无论如何都为该异常创建一个异常类,因此您可以在该类中收集一系列问题.
First of all, exceptions are costly, so you don''t want to throw them multiple time. What I would suggest is that you collect all the issues in the exception, create a class that can contain this infomration that is derived from exception. You will probably want a specific exception for this issue anyway. Then you can catch this specific excpetion, and it will have all the information about the issue. Since you are creating an exception class for this exception anyway, you can have a collection of issues in the class.


这篇关于从类中抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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