I’m a very new to java, just trying to run some simple programs.
I have this code:
import java.net.*;
import java.io.*;
class example1 {
public static void main(String args[]){
try{
URL hp = new URL("http://www.java2s.com");
System.out.println("it all worked?");
}catch (MalformedURLException e){
System.err.println("New URL failed");
System.err.println("exception thrown: " + e.getMessage());
}
System.out.println(hp.getProtocol());
}
}
The java compiler “cannot find symbol: hp” which would lead me to believe that the url object, hp is not being created by the line:
URL hp = new URL("http://www.java2s.com");
But shouldn’t the catch statement be reporting an error?
I tried compiling without the try-catch blocks but I was getting an error saying “unreported exception MalformedURLException; must be caught or declared to be thrown”
If i remove the last line that refers to hp, the program compiles and runs but just displays “it all worked?”.
I’m sure there is a simple explanation here but I don’t have much knowledge of java.
Thanks
The other answers have given you some useful advice on avoiding the error. But I would like to try to explain how your understanding of what the error means is confused.
This line:
does two things at once. It declares a variable (which is more generally referred to by the compiler as a “symbol”) named
hp, which can point to an instance of URL; and it creates an instance of URL and makeshppoint to it.You interpreted the error to mean “the url object hp is not being created”. So, first of all,
hpis not an object — it is at most a reference to an object, and of course it can also benull, in which case it is a reference to nothing. But the symbolhpexists, within the scope of its declaration, regardless of whether an object reference is assigned to it.If the object creation had failed — i.e. the
new URL ...portion of the statement had failed — then most likely an exception would have occurred as you expected. But even if for some obscure reason the creation had failed but not thrown an exception, the likely result would be thathpwould benull, in which case a valid attempt to dereference the variablehpwould result in aNullPointerException.All of which is just to illustrate that the error you received has nothing to do with whether
hphas been assigned a value, and simply indicates thathphas not been declared within the scope in which you are attempting to use it.The issue is that a
tryblock creates its own scope, so variables declared within it are not accessible outside the block. You would receive exactly the same error if the first line inside yourtryblock read simplyURL hp;. As shown in the other answers, the resolution to this is to declarehpoutside thetryblock, so that the later reference is valid. (It would also work to move the last line into thetryblock, but it makes sense to limit the contents of that block only to the statements that require the specific error handling.)