异常消息为空?为空、异常、消息

2023-09-08 09:22:58 作者:星星的轨迹

我有一个的try-catch 语句在我的code。在我的catch块,我打电话 e.getMessage()打印异常的消息。然而, e.getMessage 保持返回空值。有趣的是,当我打电话 e.printStackTrace,我没有问题,打印堆栈跟踪。

I have a try-catch statement in my code. In my catch block, I am calling e.getMessage() to print the message of the exception. However, e.getMessage keeps returning a null value. Interestingly, when I call e.printStackTrace, I have no problem printing the stack trace.

下面是我的code:

try
{
    console = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
}catch(Exception e)
{
    Log.d("Error", "Error Message: " + e.getMessage()); //e.getMessage is returning a null value
    e.printStackTrace(); //this works. is displaying a SocketTimeOutException
}

可能是什么我的问题的原因是什么?我该如何解决呢?

What could be the cause of my problem? How do I solve it?

推荐答案

的消息和堆栈跟踪是两个截然不同的部分信息。而stackstrace是强制性的,该消息是没有的。大多数例外携带消息,它是这样做的最佳做法,但有些只是不并没有什么工作要做,以解决它。

The message and the stacktrace are two distinct pieces of information. While the stackstrace is mandatory, the message is not. Most exceptions carry a message, and it is the best practice to do so, but some just don't and there's nothing to be done to fix it.

您可以为您的客户更容易,但并通过包装消息少异常或抛出一个自定义异常与原来的异常作为事业提供消息。这可能看起来像下面。

You can make it easier for your clients though and provide a message by wrapping the message-less exception or throwing a custom exception with the original exception as the cause. This might look like following.

throw new  MyRuntimeException("Socket was closed unexpectedly", e);