throw an exception

When implementing your own methods, you should throw an exception when the method

cannot complete its task as indicated by its name. When you want to throw an exception,

there are two issues that you really need to think about and consider:

• What Exception-derived type are you going to throw? You really want to select a type

that is meaningful here. Consider the code that is higher up the call stack and how that

code might want to determine that a method failed in order to execute some graceful

recovery code. You can use a type that is already defined in the FCL, but there may not

be one in the FCL that matches your exact semantics. So you'll probably need to define

your own type, derived directly from System.Exception. If you want to define an exception

type hierarchy, it is highly recommended that the hierarchy be shallow and wide in

order to create as few base classes as possible. The reason is that base classes act as a way

of treating lots of errors as one error, and this is usually dangerous. Along these lines,

you should never throw a System.Exception type, and you should use extreme caution

if you do throw any other base class exception type.

• What string message are you going to pass to the exception type's constructor? When

you throw an exception, you should include a string message with detailed information

indicating why the method couldn't complete its task. If the exception is caught and

handled, this string message is not seen. However, if the exception becomes an unhandled

exception, this message is usually logged. An unhandled exception indicates a true

bug in the application, and a developer must get involved to fix the bug. An end user will

not have the source code or the ability to fix the code and re-compile it. In fact, this

string message should not be shown to an end user. So these string messages can be

very technically detailed and as geeky as is necessary to help developers fix their code.

Furthermore, since all developers have to speak English (at least to some degree, since

programming languages and the FCL classes and methods are in English), there is usually

no need to localize exception string messages. However, you may want to localize

the strings if you are building a class library that will be used by developers who speak

different languages. Microsoft localizes the exception messages thrown by the FCL,

since developers all over the world will be using this class library.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值