如何以友好的方式在java中显示错误消息

时间:2014-10-10 13:40:12

标签: java

我有一个问题,因为我是java的初学者,你可能会发现它很愚蠢。

我正在编写一个读取文件的方法,当它不存在时,只显示错误。

File f = new File(FILE_path);
            if (f.exists() && f.canRead()) {
                try {
                    //Do something
                } catch (IOException e) {
                    e.printStackTrace();
                    LOGGER.error("Error message: " + e.getMessage());
                }
            } else {
                LOGGER.error("File does not exist or it cannot be read.");
            }

但除了显示红色错误的错误之外,还会显示,然后程序停止。

 Exception in thread "main" java.io.FileNotFoundException: /home/project/file_path (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)

现在我的问题是,无论如何该程序没有冻结在这个级别,我们只显示友好的消息?或者我们无法避免这种情况,即使我们使用try和catch,也会出现此异常错误?

2 个答案:

答案 0 :(得分:1)

你总是可以使用joptionpanes:

File f = new File(FILE_path);
        if (f.exists() && f.canRead()) {
            try {
                //Do something
            } catch (IOException e) {
                JOptionPane.showMessageDialog (null, "Something went Wrong", "Title", JOptionPane.ERROR_MESSAGE);
                LOGGER.error("Error message: " + e.getMessage());
            }
        } else {
            LOGGER.error("File does not exist or it cannot be read.");
        }

答案 1 :(得分:0)

is there anyway that the program does not freeze at this level and we show only the friendly message?

是。您的IDE(eclipse或其他)可能会在e.printStackTrace(); 之后自动将catch (IOException e)放在行上。但您不需要这样做。更有经验的程序员会说这完全没必要

当您在Java中catch异常时,您将在异常发生后获得控制权。在catch之后,您可以在程序中的任何其他位置执行任何操作。您无需打印堆栈跟踪。

听起来你只想要这个:

`catch (IOException e) {
    LOGGER.error("Error message: " + e.getMessage());
}

编辑如果您在catch区块中拥有全部内容,那么这是异常后唯一会发生的事情。你的程序不会在catch块之外/之后进行。

相关问题