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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25473850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:27:54  来源:igfitidea点击:

How to get an exception message in a String variable in java?

java

提问by Anand Maheshwari

I need to process an exceptionmessage when any exception is caught in Java.

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

I am working on a Database Connection class. When I give wrong details like username, password, host name, sid, etc, the control goes to catchblock and gives an error. I would like to get this error message on the JSP side and redirect to the same page with that error message. However, when I get the error message in Java, it always takes a null value.

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

My code example is here.

我的代码示例在这里。

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);
}

It will go to Exception block but the errorMessage is null.

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

回答by Artem Moskalev

This block is always executed:

这个块总是被执行:

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

If your errorMessagehas not been assigned any other value before (ie. no exception thrown in your tryclause) - System.out.printlnwill print you the errorMessagevalue which is null.

如果您errorMessage之前没有被分配任何其他值(即您的try子句中没有抛出异常) -System.out.println将打印您的errorMessage值,即null.

回答by Bimalesh Jha

your catch(Exception e)block will catch all exceptions (other than SQLExceptionwhich you are specifically catching above). Some exceptions e.g. NullPointerExceptioncan have null details message i.e. e.getMessage()can retun null. So it is better to print the exception details like exception type also- use e.ToString()or e.printStacktrace()for more details.

您的catch(Exception e)块将捕获所有异常(除了SQLException上面专门捕获的异常)。一些例外,例如可以有空NullPointerException详细信息,即e.getMessage()可以返回空。因此最好打印异常详细信息,例如异常类型也-使用e.ToString()e.printStacktrace()获取更多详细信息。

回答by ConcurrentHashMap

At first, the answer of @Artem Moskalev should be right in most ways. In your case, you'd said:

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

It will goes to Exception block but the errorMessage is null.

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

So, let's try two cases to debug the behavior:

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

First:

第一的:

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);
            }
    }
}

Output:

输出:

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

Seems to work like you expected.

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



Second:

第二:

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);
            }
    }
}

Output:

输出:

In Exception block.
null

Why is that? Because you're accessing e.getMessage(), but if the message is emtpy e.getMessage()will return null. So the nullisn't from the initialization, but from the return value of e.getMessage(), when edoesn't have any error message (for example if there is a NullPointerExceptionthrown).

这是为什么?因为您正在访问e.getMessage(),但是如果消息为 emtpye.getMessage()将返回null。所以 thenull不是来自初始化,而是来自e.getMessage(), when的返回值e没有任何错误消息(例如,如果有一个NullPointerException抛出)。

回答by Kayaman

Using getMessage()is worthless, you want either e.printStackTrace()(for really simple programs), or for any proper error handling use the logging framework which allows write code like log.error("Something went wrong", e);.

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