当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。
起初,@ 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
抛出)。
始终执行此块:
...finally{
System.out.println(errorMessage);
}
如果你的errorMessage
之前没有被赋予任何其他值(即你的try
条款中没有例外) - System.out.println
将打印errorMessage
值null
。
你的catch(Exception e)
块将捕获所有异常(除了你特别在上面捕获的SQLException
)。例如一些例外NullPointerException
可以有null详细消息,即e.getMessage()
可以重新调用null。因此最好打印异常类型,例如异常类型 - 使用e.ToString()
或e.printStacktrace()
获取更多详细信息。
使用getMessage()
是没有价值的,你需要e.printStackTrace()
(对于非常简单的程序),或者对于任何正确的错误处理使用允许编写代码如log.error("Something went wrong", e);
的日志框架。