Java:异常作为控制流? [英] Java: Exceptions as control flow?

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

问题描述

我听说使用控制流的例外是不好的做法。你觉得这是什么?

I've heard that using exceptions for control flow is bad practice. What do you think of this?

public static findStringMatch(g0, g1) {

    int g0Left = -1;
    int g0Right = -1;
    int g1Left = -1;
    int g1Right = -1;

//if a match is found, set the above ints to the proper indices
//...
//if not, the ints remain -1

        try {
            String gL0 = g0.substring(0, g0Left);
            String gL1 = g1.substring(0, g1Left);

            String g0match = g0.substring(g0Left, g0Right);
            String g1match = g1.substring(g1Left, g1Right);

            String gR0 = g0.substring(g0Right);
            String gR1 = g1.substring(g1Right);

            return new StringMatch(gL0, gR0, g0match, g1match, gL1, gR1);
        }
        catch (StringIndexOutOfBoundsException e) {
            return new StringMatch(); //no match found
        }

所以,如果没有找到匹配,将为-1。当我尝试使用 g0.substring(0,-1)的子字符串时,这将导致异常。那么函数只是返回一个表示没有匹配的对象。

So, if no match has been found, the ints will be -1. This will cause an exception when I try to take the substring g0.substring(0, -1). Then the function just returns an object indicating that no match is found.

这是不好的做法吗?我可以手动检查每个索引,看看它们是否全部为-1,但是感觉像更多的工作。

Is this bad practice? I could just check each index manually to see if they're all -1, but that feels like more work.

更新

我已经删除了try-catch块,并将其替换为:

I have removed the try-catch block and replaced it with this:

    if (g0Left == -1 || g0Right == -1 || g1Left == -1 || g1Right == -1) {
        return new StringMatch();
    }

哪个更好:检查每个变量是否为-1,或使用布尔值 foundMatch 跟踪,只是在最后检查?

Which is better: checking if each variable is -1, or using a boolean foundMatch to keep track and just check that at the end?

推荐答案

一般来说,例外是昂贵的操作,正如名字所示,异常情况。所以在控制应用程序的流程中使用它们确实被认为是不好的做法。

Generally exceptions are expensive operations and as the name would suggest, exceptional conditions. So using them in the context of controlling the flow of your application is indeed considered bad practice.

具体在你提供的例子中,你需要做一些基本的验证您提供给StringMatch构造函数的输入。如果它是返回错误代码的方法,以防某些基本参数验证失败,您可以避免事先检查,但情况并非如此。

Specifically in the example you provided, you would need to do some basic validation of the inputs you are providing to the StringMatch constructor. If it were a method that returns an error code in case some basic parameter validation fails you could avoid checking beforehand, but this is not the case.

这篇关于Java:异常作为控制流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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