如何在java中的String变量中获取异常消息?

时间:2014-08-24 16:34:52

标签: java

当Java中捕获到任何异常时,我需要处理异常消息。

我正在研究数据库连接类。当我提供错误的详细信息,如用户名,密码,主机名,sid等时,控件将转到 catch 块并发出错误。我想在JSP端获取此错误消息并重定向到具有该错误消息的同一页面。但是,当我在Java中收到错误消息时,它总是需要一个空值。

我的代码示例就在这里。

String errorMessage = null;
try{
// CODE Where Exception occure
}catch(SQLException se){
    errorMessage = se.getMessage();
}catch(Exception e){
    System. out.println("In Exception block.");
    errorMessage = e.getMessage();
}finally{
    System.out.println(errorMessage);
}

它将转到Exception块,但errorMessage为null。

4 个答案:

答案 0 :(得分:9)

起初,@ Artem Moskalev的回答在大多数方面应该是正确的。在你的情况下,你说:

  

它将转到Exception块,但errorMessage为null。

因此,让我们尝试两种情况来调试行为:

<强>首先

class Test1
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String errorMessage = null;
            try{
                throw(new Exception("Let's throw some exception message here"));
            }catch(Exception e){
                System.out.println("In Exception block.");
                errorMessage = e.getMessage();
            }finally{
                System.out.println(errorMessage);
            }
    }
}

输出:

In Exception block.
Let's throw some exception message here

似乎像你期望的那样工作。


<强>第二

class Test2
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // String errorMessage = null;
        // To make the difference between non-initialized value 
        // and assigned null value clearer in this case,
        // we will set the errorMessage to some standard string on initialization
        String errorMessage = "Some standard error message";
            try{
                throw(new Exception());
            }catch(Exception e){
                System.out.println("In Exception block.");
                errorMessage = e.getMessage();
            }finally{
                System.out.println(errorMessage);
            }
    }
}

输出:

In Exception block.
null

为什么?因为您正在访问e.getMessage(),但如果邮件是emtpy e.getMessage(),则会返回null。因此null不是来自初始化,而是来自e.getMessage()的返回值,当e没有任何错误消息时(例如,如果有的话)抛出NullPointerException

答案 1 :(得分:2)

此块始终执行:

...finally{
    System.out.println(errorMessage);
}

如果之前未向errorMessage分配任何其他值(即try条款中没有异常),则System.out.println会打印errorMessagenull是{{1}}。

答案 2 :(得分:2)

您的catch(Exception e)区块将捕获所有异常(除了SQLException以外您特别关注的异常)。例如一些例外NullPointerException可以包含null详细消息,即e.getMessage()可以重新返回null。因此,最好打印异常类型,例如异常类型 - 使用e.ToString()e.printStacktrace()以获取更多详细信息。

答案 3 :(得分:2)

使用getMessage()毫无价值,您需要e.printStackTrace()(对于非常简单的程序),或者对于任何正确的错误处理,使用允许编写代码log.error("Something went wrong", e);的日志框架。