在try..catch块总是贵吗? [英] Try..Catch blocks always expensive?

查看:257
本文介绍了在try..catch块总是贵吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
不要试图/时异常不抛出catch块伤的性能?

大家好,
只是一个快速的约在try..catch块的问题。我听到他们使用昂贵的,不应该被用来作为一个程序的流的一部分。但是,为了验证电子邮件地址,我用下面的代码。

Hey everyone, Just a quick question about try..catch blocks. I've heard they're expensive to use and shouldn't be used as part of a program's flow. However, in order to validate email addresses, I'm using the following code.

        try
        {
            MailAddress checkEmail = new MailAddress(testEmail);

            return true;
        }
        catch
        {
            return false;
        }



由于事先验证,我被抓不是很多例外,除非它是企图绕过验证。我的问题是,是的try ... catch块只有昂贵的,如果一个异常被捕获,或者是它的总是的昂贵,无论任何异常是否抛出?

Due to prior validation, I don't many exceptions to be caught unless it's an attempt to bypass validation. My question is, are Try...Catch blocks only expensive if an exception is caught, or is it always expensive regardless of whether any exception is thrown?

感谢

修改的:感谢所有的答复。我决定,既然检查(在C#)不是很贵,我会用这种方法坚持下去。这主要是因为因为是确保没有人不小心输入了无效的电子邮件地址之前的验证步骤被抛出一个实际的例外是罕见的。

EDIT : Thanks for all the replies. I've decided that since the checking (in C#) isn't very expensive, I'll stick with this method. It's mainly because an actual exception being thrown is rare since there are prior validation steps that ensure no one accidentally enters an invalid email address.

推荐答案

这是很难回答这个问题,而不必提到什么样的环境你在谈论(Java,C#,...)。

It's very hard to answer this question without your having mentioned what environment you're talking about (Java, C#, ...).

一般的,在今天的实施,进入了一个尝试块是不是在所有昂贵(这并不总是如此)。然而,抛出和处理一个的例外的通常是一个昂贵的操作。所以,异常应该仅用于例外的事件。例如,当你打开用户已给出了路径,使用任何环境提供了第一个文件是否存在来检查文件,即使打开操作将引发 FileNotFoundException异常或者如果它不相似。支票将便宜;处理该异常可能不是。

In general, in today's implementations, entering a try block is not expensive at all (this was not always true). However, throwing and handling an exception is usually an expensive operation. So, exceptions should only be used for exceptional events. For example, when you're opening a file that a user has given the path for, use whatever your environment provides to check first whether the file exists, even if the "open" operation will throw a FileNotFoundException or similar if it doesn't. The check will be cheap; processing the exception may not be.

这篇关于在try..catch块总是贵吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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