gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:33:22 25 4
gpt4 key购买 nike

当在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com