Other answers have given you some helpful tips for preventing errors. But I would like to try to explain how your understanding of what error means is confused.
This line:
URL hp = new URL("http://www.java2s.com");
does two things at once. It declares a variable (which is generally referred to by the compiler as a "character") with the name hp , which can point to an instance of a URL; and he creates an instance of the url and makes hp for it.
You interpreted the error as meaning "hp urp object is not created." So, first of all, hp not an object - it is most likely a reference to an object, and, of course, it can be null , and in this case it is a reference to nothing. But the hp symbol exists within its declaration, regardless of whether an object reference is assigned to it.
If the creation of the object failed - i.e. part of the new URL ... statement new URL ... this operator failed - most likely the exception would have occurred as you expected. But even if, for some unclear reason, the creation failed but did not raise an exception, the likely result would be that hp would be null , in which case a valid attempt to dereference the hp variable would result in a NullPointerException .
All this just illustrates that the error you received has nothing to do with whether hp was assigned a value and simply indicates that hp not declared in the area in which you are trying to use it.
The problem is that the try block creates its own scope, so the variables declared inside it are not available outside the block. You will get exactly the same error if the first line inside the try block just reads the URL hp; . As shown in other answers, permission to do this is to declare hp outside the try block, so that a later reference is valid. (It would also work to move the last line into a try block, but it makes sense to limit the contents of this block only to statements that require specific error handling.)
source share