无法在 eclipse (java) 中创建 ServerSocket
我对 Java 编程很陌生,但在 .NET(c# 和 vb.net)方面有很多经验。
我正在尝试在 Eclipse IDE 中创建一个 serversocket 类的新实例,当我输入以下代码时,它给了我一个“未处理的异常类型 IOException”,我什至还没有尝试运行该代码!
我不明白我的代码在运行时之前如何出现异常,也不明白我可以采取什么措施来修复它。
有人可以帮助我吗?
违规代码:
ServerSocket server = new ServerSocket(1234, 5, InetAddress.getLocalHost());
i am very new to programming in java however have a lot of experience in .NET (c# & vb.net).
I am trying to create a new instance of a serversocket class in eclipse IDE and when i type the following code it is giving me an "Unhandled exception type IOException" and i havent even tried to run the code yet!!
I dont understand how my code is exceptioning before runtime or what i can do to fix it.
Can someone help me?
Offending code:
ServerSocket server = new ServerSocket(1234, 5, InetAddress.getLocalHost());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果在编辑时在java文件中给出“未处理的异常类型IOException”,则意味着您需要包含此语句
在 try-catch 块中
try{
ServerSocket server = new ServerSocket(1234, 5, InetAddress.getLocalHost());
}catch(IOException ex){
e.printStackTrace();
}
If it is giving "Unhandled exception type IOException", in java file while editing, it means that you need to enclose this statement
in try-catch block
try{
ServerSocket server = new ServerSocket(1234, 5, InetAddress.getLocalHost());
}catch(IOException ex){
e.printStackTrace();
}
这是 Java 语言的一个功能,称为 检查异常。基本上,您调用的代码中存在可以在编译时确定的异常。 Java 语言设计者认为强制您处理它们是明智的做法。
在本例中,ServerSocket 类构造函数在其方法签名中声明它抛出 IOException。
有两种方法可以消除编译错误。
您可以将代码包装在 try/catch 中。
或者,您可以将责任传递给调用方法。例如,假设您在名为
createSocket()
的方法内调用了ServerSocket
构造函数。您可以像这样声明您的方法,在这种情况下,您只是将责任转移到调用链上,但有时这是有意义的。
这在 Java 语言中非常常见,以至于 Eclipse 提供了上述两个选项作为快速修复。
This is a feature of the Java language called Checked Exceptions. Basically, there are Exceptions in code that you call that can be determined at compile time. The Java language designers thought it prudent to force you to handle them.
In this case the ServerSocket class constructor, in its method signature, declares that it throws an IOException.
There are two ways to make the compile error go away.
You can wrap the code in a try/catch.
Or, you can pass responsibility on to the calling method. For example, suppose you called the
ServerSocket
constructor inside a method calledcreateSocket()
. You would declare your method like soIn this case, you're just moving responsibility up the call chain, but sometimes that makes sense.
This is so common in the Java language, that Eclipse offers the two options above as Quick Fixes.