java URL 对象 - 新的 java.net.URL()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7681877/
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
java URL object - new java.net.URL()
提问by Mike Monteith
I'm a very new to java, just trying to run some simple programs. I have this code:
我是java的新手,只是想运行一些简单的程序。我有这个代码:
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:
java 编译器“找不到符号:hp”这会让我相信 url 对象 hp 不是由以下行创建的:
URL hp = new URL("http://www.java2s.com");
But shouldn't the catch statement be reporting an error?
但是 catch 语句不应该报告错误吗?
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"
我尝试在没有 try-catch 块的情况下进行编译,但我收到一条错误消息,提示“未报告的异常 MalformedURLException;必须被捕获或声明要抛出”
If i remove the last line that refers to hp, the program compiles and runs but just displays "it all worked?".
如果我删除引用 hp 的最后一行,程序将编译并运行,但只显示“一切正常?”。
I'm sure there is a simple explanation here but I don't have much knowledge of java. Thanks
我确定这里有一个简单的解释,但我对 java 了解不多。谢谢
回答by CoolBeans
When you define hp
inside the try-catch block, its visibility is within the try block. Hence, you get the compilation error in the print statement outside the try-catch block.
当您hp
在 try-catch 块内定义时,其可见性在 try 块内。因此,您会在 try-catch 块之外的打印语句中收到编译错误。
Define hp
before the try block begins in the following manner:-
hp
在 try 块以下列方式开始之前定义:-
URL hp = null;
try{
hp = new URL("http://www.java2s.com");
System.out.println("it all worked?");
System.out.println(hp.getProtocol());
}catch (MalformedURLException e){
System.err.println("New URL failed");
System.err.println("exception thrown: " + e.getMessage());
}
To understand this better read the section 14.4.2 Scope of Local Variable Declarations
here.
要更好地理解这一点,请阅读14.4.2 Scope of Local Variable Declarations
此处的部分。
Also for safer and proper coding practice, you should throw the MalformedURLException
that you catch with the throwclause:-
同样为了更安全和正确的编码实践,你应该抛出MalformedURLException
你用throw子句捕捉到的:-
catch (MalformedURLException e){
System.err.println("New URL failed");
System.err.println("exception thrown: " + e.getMessage());
throw new MalformedURLException("Invalid URL!");
}
You will also need to update your main to throw this exception:-
您还需要更新您的 main 以抛出此异常:-
public static void main(String[] args) throws MalformedURLException
public static void main(String[] args) throws MalformedURLException
If you do not do this your code will continue in case of a malformed URL!
如果您不这样做,您的代码将在 URL 格式错误的情况下继续运行!
回答by Dave Costa
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:
这一行:
URL hp = new URL("http://www.java2s.com");
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 makes hp
point to it.
一次做两件事。它声明了一个名为 的变量(通常被编译器称为“符号”)hp
,它可以指向 URL 的一个实例;并创建一个 URL 实例并hp
指向它。
You interpreted the error to mean "the url object hp is not being created". So, first of all, hp
is not an object -- it is at most a reference to an object, and of course it can also be null
, in which case it is a reference to nothing. But the symbol hp
exists, within the scope of its declaration, regardless of whether an object reference is assigned to it.
您将错误解释为“未创建 url 对象 hp”。所以,首先,hp
不是对象——它至多是对对象的引用,当然也可以是null
,在这种情况下,它是对空的引用。但是该符号hp
存在于其声明的范围内,无论是否为其分配了对象引用。
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 that hp
would be null
, in which case a valid attempt to dereference the variable hp
would result in a NullPointerException
.
如果对象创建失败——即new URL ...
语句的一部分失败——那么很可能会如你所料地发生异常。但是,即使由于某种晦涩的原因,创建失败但没有抛出异常,可能的结果hp
是null
,在这种情况下,对变量的有效尝试取消引用hp
将导致NullPointerException
.
All of which is just to illustrate that the error you received has nothing to do with whether hp
has been assigned a value, and simply indicates that hp
has not been declared within the scope in which you are attempting to use it.
所有这些只是为了说明您收到的错误与是否hp
已分配值无关,只是表明hp
尚未在您尝试使用它的范围内声明。
The issue is that a try
block 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 your try
block read simply URL hp;
. As shown in the other answers, the resolution to this is to declare hp
outside the try
block, so that the later reference is valid. (It would also work to move the last line into the try
block, but it makes sense to limit the contents of that block only to the statements that require the specific error handling.)
问题是一个try
块创建了它自己的作用域,所以在它内部声明的变量在块之外是不可访问的。如果try
块内的第一行只是简单地读取,您将收到完全相同的错误URL hp;
。如其他答案所示,解决方法是hp
在try
块外声明,以便后面的引用有效。(也可以将最后一行移到try
块中,但将该块的内容限制为需要特定错误处理的语句是有意义的。)