成品中的printStackTrace()。什么时候,为什么? [英] printStackTrace() in a finished product. When and why?

查看:151
本文介绍了成品中的printStackTrace()。什么时候,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从许多资料中可以得出结论,使用 printStackTrace 进行错误处理是不好的做法。 这是一个。

I've come to the conclusion after reading from many sources that using printStackTrace for error handling is bad practice. Here's one.

现在我很惊讶:在什么情况下打印stacktrace是有效的解决方案?出于争论的缘故,让我们假设我们不是在诸如微波炉或香蕉之类的系统上工作,而是在基本的现成PC上工作。

Now I'm struck curious: in what cases is printing the stacktrace a valid solution? For the sake of the argument, let's assume we aren't working on a system such as a microwave or a banana, but a basic out-of-the-shelf PC.

我问这个问题的原因本身可以看作一个问题,但是我会告诉你的:

The reason I'm asking this could be seen as a question in itself, but I'll tell you about it anyhoo:

我正在开发一条蛇,例如可以与AI一起玩的游戏。所有这些AI都应扩展名为 SnakeLogic 的抽象类。所有这些AI都还应该驻留在特定文件夹中的独立.jar存档中,主程序可以在其中找到它们并使用类加载器列出它们。

I'm developing a snake-like game that can be played with AIs, and is intended for that purpose. All such AIs should extend an abstract class called SnakeLogic. All such AIs should also reside in their standalone .jar archives in a specific folder, from where the main program can find them and list them using classloaders.

然后,用户可以从列表中选择他/她的一个AI,如果所有星星都排成一行,并使用该AI玩游戏。

The user can then choose one of his/her AIs from a list, should all stars fall in line, and play a game with this AI.

现在,我的主方法是像这样从AI获取下一步动作的程序:

Now, I have a method in my main program that gets the next move from the AI like so:

public void startGame(int speed) {        
    gameInterface.showWindow();
    Runnable moveCmd = () -> {
        try {

            for (Player player : snakeGame.getPlayers()) {
                if (player.isDead()) {
                    continue;
                }

                String move = player.getLogicHandler().getMove();

                Direction direction = Direction.directionFromString(move);
                snakeGame.makeMove(player, direction);
            }

            gameInterface.getFrame().repaint();
            snakeGame.wait(speed);

            if (snakeGame.gameOver()) {
                stopGame();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            stopGame();
        }
    };

    /* moveSchedule is an instance of ScheduledExecutorService */
    moveSchedule.scheduleAtFixedRate(moveCmd, 1000, speed, TimeUnit.MILLISECONDS);        
}

我不会太参与上面的代码。不过,我想提醒您注意try-catch语句。如您所见,我在执行 moveCmd 可运行程序期间某处发生异常的情况下,打印了堆栈跟踪并结束了游戏。这就是我的好奇心:如果我不这样打印stacktrace,或者如果我完全删除try-catch,则在执行该块期间发生运行时异常的情况下,我永远不会出错。为什么?是因为它包裹在可运行内部吗?另请注意, snakeGame.makeMove(player,direction); 行不调用主程序中的任何代码; snakeGame是 SnakeLogic 的一个实例,它位于外部.jar中。

I'm not going to get too involved with the code above. I'd like to draw your attention to the try-catch statement, however. As you can see I print the stacktrace and end the game, should an exception occur somewhere during the execution of the moveCmd runnable. This is the source of my curiosity: If I don't print the stacktrace like this, or if I remove the try-catch entirely, I never get any errors in the case of a runtime exception during the execution of that block. Why? Is it because it's wrapped inside the runnable? Note also that the line snakeGame.makeMove(player, direction); doesn't call any code in the main program; snakeGame is an instance of a SnakeLogic, which resides in an external .jar.

为什么我不明白如果删除try-catch有任何错误?另外,在这种情况下,打印stacktrace是个好主意吗?

Why don't I get any errors if I remove the try-catch? Also, in this case, is printing the stacktrace a good idea?

我知道这给您带来了两个问题:主题和上面的问题。我想强调这个话题,所以不要对第二个问题过于关注;尽管洞察力已得到适当记录,但我的代码没有任何问题。

I understand this imposes two questions for you: the topic and the above. I want to emphasize the topic, so don't get too sidetracked with the second question; though insight is duly noted, there's nothing broken in my code.

推荐答案

在处理时,您需要稍微改变一下思维过程错误和异常。打印错误跟踪始终是一个好习惯。现在的问题是在哪里打印。默认情况下, printStackTrace 打印到标准控制台。当然,您可以像Tomcat一样将输出重定向到日志文件,但是如果您询问我,也可以解决。

You need to shift your thought process a bit when dealing with error and exceptions. It is always a good practice to print the error trace. Now the question is where to print. by default printStackTrace prints to your standard console. of course you can redirect that output to a log file like Tomcat does but that is a work around, if you ask me.

在生产和生产前系统中,甚至在可分发的spftware中,您可以在其中将桌面应用程序分发给用户以在PC上运行,您可能具有也可能没有控制台专用访问权限。关闭控制台或应用完成后,控制台上的打印内容也会丢失。您需要将错误保留在某处,以便稍后进行分析。通常,人们将应用程序设计为压缩并定期将错误日志发送给开发人员进行分析。

In production and pre-prod systems and even in distributable spftware where you distribute a desktop application to users for running on PCs you may or may not have dedicated access to console. Further more what prints on console is lost once the console is closed or app finishes. You need to persist the errors somewhere for analysis later. Normally folks design the app to zip and send error logs periodically to developers for analysis.

现在,如果您考虑整个场景,最重要的是将错误保存在某个地方稍后分析。因此,通常在循环日志文件或数据库中进行操作。控制台不足。因此顺便说一句,catch块应该有一个log语句来记录异常。

Now if you think about the whole scenarios the bottom line is to preserve the errors somewhere for analysis later. So usually do it in a rotating log file or in DB. Console wont suffice. Thus incidentally the catch block should have a log statement to log the exception.

这篇关于成品中的printStackTrace()。什么时候,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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