异常处理 [英] Exception Handling

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

问题描述

结构化异常处理是否坏?处理异常的正确方法是什么?



编辑:使用C#的.NET异常处理



我通常有一组特定的异常类(DivideByZeroException,ArrayTypeMismatchException),没有一个通用的catch(Exception ex)。



这背后的想法是,我希望某些类型的异常发生,并在发生特定的操作时定义特定的操作,并且意外的异常将会升高到界面(Windows或Web)。这是一个好习惯吗?

解决方案

我不知道结构化异常处理是什么意思。



异常处理中可以做的最糟糕的事情是吞下异常或静默处理。



不要这样做:

  try {
...
}
catch (例外e){
// TODO:稍后处理
}

这通常是由于懒惰得到代码来编译的。如果您不知道如何处理特定级别的异常,请使用该方法抛出异常,并至少有一个catch顶部的所有处理程序。提供反馈(通过GUI,一个页面/电子邮件给支持人员,日志文件),以便最终可以解决问题。悄悄地捕捉异常几乎总是导致一个更大的问题发生在后面,很难追踪。


Is Structured Exception Handling bad? What is the right way to handle exceptions?

EDIT: Exception Handling in .NET using C#.

I usually have a set of specific exception classes (DivideByZeroException, ArrayTypeMismatchException) and don't have a generic "catch (Exception ex)".

The thinking behind this is that I expect certain types of exceptions to occur and have specific actions defined when they occur and the unexpected exceptions would rise up the the interface (either windows or web). Is this a good practice?

解决方案

I'm not sure what you mean by 'structured exception handling'.

The worst thing that can be done in exception handling is to 'swallow' the exception or handle it silently.

Do NOT do this:

try {
   ...
}
catch (Exception e) {
   //TODO: handle this later
}

This is very often done out of laziness to get code to compile. If you do not know how to handle the exception at a particular level, have the method throw the exception and at least have a catch all handler at the top. Provide feedback somehow (via the GUI, a page / email to a support person, log file) so that the issue can eventually get fixed. Silently catching an exception almost always leads to a bigger issue happening later on and it being difficult to trace.

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

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