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

标签 java

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

我正在研究数据库连接类。当我提供错误的详细信息(如用户名、密码、主机名、sid 等)时,控件会转到 catch block 并给出错误。我想在 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 block ,但 errorMessage 为空。

最佳答案

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

It will goes to Exception block but the errorMessage is 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(),但是如果消息为空,e.getMessage() 将返回 null。所以null不是来自初始化,而是来自e.getMessage()的返回值,当e没有任何错误消息(例如,如果抛出 NullPointerException)。

关于java - 如何在 java 中的 String 变量中获取异常消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25473850/

相关文章:

javascript - 日期和时间相关的客户端服务器 Web 应用程序

java - 无法使用 jbdc updateRow 方法更新 Oracle IOT 表

java - 如何动态地将多个值添加到HashMap中的单个键上?

java - 如何从数据库生成对象@Entities?

java - Hybris 租户就像一个进程吗?

java - JFreeChart - OHLC 和普通的 TimeSeries

java - Gson反序列化为 map

java - Gridgain:java.lang.OutOfMemoryError:超出 GC 开销限制

java - 如何只设置一次文本,但它涉及到许多 Activity

java - 在一行中实例化数组的数组