长时间尝试声明 [英] Long try statements

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

问题描述

将大多数函数代码放在 try语句中是否有任何缺点。如果我执行需要 try语句的操作,通常我会在try语句中为此功能做很多工作,因为我通常在那声明变量,并且可以如果这样做,请勿在该范围之外使用它们。这是常见的吗?人们通常会在不初始化变量之前就声明变量,这样他们就不会在 try语句内做任何事情(包括对其他函数的调用)吗?还是很长很重要?

Is there any drawback to putting most of your code for your function in a try statement. If I do something that requires a try statement, I usually end up doing a lot of work for that function inside the try statement because I usually declare my variables in there and can't use them outside that scope if I do that. Is this common and accepted? Do people usually declare variable before without initializing them so they're not doing everything (including calls to other functions) inside a try statement? Or does it not matter if it's very long?

推荐答案

一种方法应该做一件事并且做得很好。在这种情况下,您的方法做两件事:业务逻辑和错误处理:

A method should do one thing and do it good. In this case your method is doing two things: business logic and error handling:

public Foo bar() {
    try {
        //business logic that may throw
        //...
        //end even more
    } catch(BuzzException e) {
        //Error handling
    }
}

我经常发现自己提取<$的内容c $ c> try 块成一个没有错误处理的单独方法:

Very often I find myself extracting the contents of try block into a separate method without error handling:

public Foo bar() {
    try {
        return unsafeBar();
    } catch(BuzzException e) {
        //Error handling
    }
}

public Foo unsafeBar() throws BuzzException {
    //business logic that may throw
    //...
    //end even more
}

这篇关于长时间尝试声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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