Java Exceptions, pass data from try block to the handler

164 views Asked by At

I am catching a MalformedURLException and I would like the stack trace to include the malformed url.

The methods getMessage() and getLocalisedMessage() don't show the entire URL, I cannot reference the url declared in the try block and if I initialise the variable outside the block I get an error pointing out that the URL might not ever get initialised.

I am wondering if there is a way to pass the url from the try block to the handler.

2

There are 2 answers

0
Nir Alfasi On BEST ANSWER

When you declare the URL outside the try block init it to null

0
federicoviscomi On

assuming your code is like this

try {
      throw new MalformedURLException("message");
} catch (MalformedURLException e) {
      e.getStackTrace();
      e.getCause(); // in this case e.getCause() == e
      e.getMessage();
}

in the catch block you can only access the stack trace, the message and the exception.

If e.getMessage() contains the full URL you can access the full URL otherwise there is no solution and you have to work on the code that trows the exception